blob: f747cf9979cb566495f47409608a0ae9e1ff970e [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chenb3b92582015-12-07 11:22:13 -080019import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070021import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070022import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070023import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070024import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070026import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070031import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070032import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080033import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070035import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080038import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070039import android.os.Environment;
40import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080041import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080043import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010044import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070045import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080046import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070048import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070049import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040050import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070051import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070052import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070053import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070054import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080055import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010056import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070057import android.os.storage.VolumeInfo;
58import android.system.ErrnoException;
59import android.system.Os;
60import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070061import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070062import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import android.util.Slog;
64import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080065import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070066import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import android.util.Xml;
68
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070070import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040071import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080072import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080073import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070074import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070075import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000076import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070077import com.android.server.LocalServices;
Jeff Sharkey0e62384c2016-01-13 18:52:55 -070078import com.android.server.pm.Installer.StorageFlags;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080079
80import org.xmlpull.v1.XmlPullParser;
81import org.xmlpull.v1.XmlPullParserException;
82import org.xmlpull.v1.XmlSerializer;
83
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084import java.io.BufferedOutputStream;
85import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070086import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070088import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070089import java.io.FileOutputStream;
90import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070091import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010092import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093import java.util.ArrayList;
94import java.util.List;
95
Fyodor Kupolov262f9952015-03-23 18:55:11 -070096import libcore.io.IoUtils;
Xiaohui Chenb3b92582015-12-07 11:22:13 -080097import libcore.util.Objects;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070098
Makoto Onuki068c54a2015-10-13 14:34:03 -070099/**
100 * Service for {@link UserManager}.
101 *
102 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700103 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800104 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700105 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
106 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
107 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700108 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700109public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700110 private static final String LOG_TAG = "UserManagerService";
Amith Yamasani12747872015-12-07 14:19:49 -0800111 static final boolean DBG = true; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800112 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700113
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800115 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700117 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700119 private static final String ATTR_CREATION_TIME = "created";
120 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700121 private static final String ATTR_SERIAL_NO = "serialNumber";
122 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700123 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700124 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700125 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100126 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700127 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800128 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
129 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530130 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700131 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800133 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800134 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800135 private static final String TAG_ENTRY = "entry";
136 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800137 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800138 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700139 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800140 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700142 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
143 private static final String ATTR_TYPE_STRING = "s";
144 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700145 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700146 private static final String ATTR_TYPE_BUNDLE = "B";
147 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700148
Amith Yamasani0b285492011-04-14 17:35:23 -0700149 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700150 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700151 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100152 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700153
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800154 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700155 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800156
Amith Yamasani634cf312012-10-04 17:34:21 -0700157 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700158 // We need to keep process uid within Integer.MAX_VALUE.
159 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700160
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700161 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700162
Amith Yamasani920ace02012-09-20 22:15:37 -0700163 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
164
Nicolas Prevotb8186812015-08-06 15:00:03 +0100165 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700166 // without first making sure that the rest of the framework is prepared for it.
167 private static final int MAX_MANAGED_PROFILES = 1;
168
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800169 static final int WRITE_USER_MSG = 1;
170 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530171
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700172 private static final String XATTR_SERIAL = "user.serial";
173
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800174 // Tron counters
175 private static final String TRON_GUEST_CREATED = "users_guest_created";
176 private static final String TRON_USER_CREATED = "users_user_created";
177
Dianne Hackborn4428e172012-08-24 17:43:05 -0700178 private final Context mContext;
179 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700180 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700181 // Short-term lock for internal state, when interaction/sync with PM is not required
182 private final Object mUsersLock = new Object();
183 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700184
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800185 private final Handler mHandler;
186
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700187 private final File mUsersDir;
188 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700189
Makoto Onuki068c54a2015-10-13 14:34:03 -0700190 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800191 * User-related information that is used for persisting to flash. Only UserInfo is
192 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800193 */
Amith Yamasani12747872015-12-07 14:19:49 -0800194 private static class UserData {
195 // Basic user information and properties
196 UserInfo info;
197 // Account name used when there is a strong association between a user and an account
198 String account;
199 // Account information for seeding into a newly created user. This could also be
200 // used for login validation for an existing user, for updating their credentials.
201 // In the latter case, data may not need to be persisted as it is only valid for the
202 // current login session.
203 String seedAccountName;
204 String seedAccountType;
205 PersistableBundle seedAccountOptions;
206 // Whether to perist the seed account information to be available after a boot
207 boolean persistSeedData;
208
209 void clearSeedAccountData() {
210 seedAccountName = null;
211 seedAccountType = null;
212 seedAccountOptions = null;
213 persistSeedData = false;
214 }
215 }
216
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800217 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800218 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800219
220 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700221 * User restrictions set via UserManager. This doesn't include restrictions set by
222 * device owner / profile owners.
223 *
224 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
225 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
226 * maybe shared between {@link #mBaseUserRestrictions} and
227 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
228 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700229 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700230 */
231 @GuardedBy("mRestrictionsLock")
232 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
233
234 /**
235 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
236 * with device / profile owner restrictions. We'll initialize it lazily; use
237 * {@link #getEffectiveUserRestrictions} to access it.
238 *
239 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
240 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
241 * maybe shared between {@link #mBaseUserRestrictions} and
242 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
243 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700244 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700245 */
246 @GuardedBy("mRestrictionsLock")
247 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
248
Makoto Onuki4f160732015-10-27 17:15:38 -0700249 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800250 * User restrictions that have already been applied in
251 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
252 * that have changed since the last
253 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700254 */
255 @GuardedBy("mRestrictionsLock")
256 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
257
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800258 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800259 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
260 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800261 */
262 @GuardedBy("mRestrictionsLock")
263 private Bundle mDevicePolicyGlobalUserRestrictions;
264
265 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800266 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
267 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800268 */
269 @GuardedBy("mRestrictionsLock")
270 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
271
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800272 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530273 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800274
275 /**
276 * Set of user IDs being actively removed. Removed IDs linger in this set
277 * for several seconds to work around a VFS caching issue.
278 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700279 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800280 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700281
Fyodor Kupolov82402752015-10-28 14:54:51 -0700282 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700283 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800284 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700285 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700286 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700287
Jason Monk62062992014-05-06 09:55:28 -0400288 private IAppOpsService mAppOpsService;
289
Makoto Onuki068c54a2015-10-13 14:34:03 -0700290 private final LocalService mLocalService;
291
Makoto Onukie7927da2015-11-25 10:05:17 -0800292 @GuardedBy("mUsersLock")
293 private boolean mIsDeviceManaged;
294
295 @GuardedBy("mUsersLock")
296 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
297
Makoto Onukid45a4a22015-11-02 17:17:38 -0800298 @GuardedBy("mUserRestrictionsListeners")
299 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
300 new ArrayList<>();
301
Clara Bayarria1771112015-12-18 16:29:18 +0000302 private final LockPatternUtils mLockPatternUtils;
303
Amith Yamasani258848d2012-08-10 17:06:33 -0700304 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700305
Dianne Hackborn4428e172012-08-24 17:43:05 -0700306 public static UserManagerService getInstance() {
307 synchronized (UserManagerService.class) {
308 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700309 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700310 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700311
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800312 @VisibleForTesting
313 UserManagerService(File dataDir) {
314 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700315 }
316
Dianne Hackborn4428e172012-08-24 17:43:05 -0700317 /**
318 * Called by package manager to create the service. This is closely
319 * associated with the package manager, and the given lock is the
320 * package manager's own lock.
321 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800322 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
323 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700324 }
325
Dianne Hackborn4428e172012-08-24 17:43:05 -0700326 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800327 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700328 mContext = context;
329 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700330 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800331 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800332 synchronized (mPackagesLock) {
333 mUsersDir = new File(dataDir, USER_INFO_DIR);
334 mUsersDir.mkdirs();
335 // Make zeroth user directory, for services to migrate their files to that location
336 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
337 userZeroDir.mkdirs();
338 FileUtils.setPermissions(mUsersDir.toString(),
339 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
340 -1, -1);
341 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
342 initDefaultGuestRestrictions();
343 readUserListLP();
344 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700345 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700346 mLocalService = new LocalService();
347 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000348 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700349 }
350
351 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100352 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800353 ArrayList<UserInfo> partials = new ArrayList<>();
354 synchronized (mUsersLock) {
355 final int userSize = mUsers.size();
356 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800357 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100358 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800359 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700360 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700361 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700362 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800363 final int partialsSize = partials.size();
364 for (int i = 0; i < partialsSize; i++) {
365 UserInfo ui = partials.get(i);
366 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
367 + " (name=" + ui.name + ")");
368 removeUserState(ui.id);
369 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800370
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700371 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800372
Jason Monk62062992014-05-06 09:55:28 -0400373 mAppOpsService = IAppOpsService.Stub.asInterface(
374 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800375
376 synchronized (mRestrictionsLock) {
377 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400378 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700379 }
380
381 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800382 public String getUserAccount(int userId) {
383 checkManageUserAndAcrossUsersFullPermission("get user account");
384 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800385 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800386 }
387 }
388
389 @Override
390 public void setUserAccount(int userId, String accountName) {
391 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800392 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800393 synchronized (mPackagesLock) {
394 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800395 final UserData userData = mUsers.get(userId);
396 if (userData == null) {
397 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
398 return;
399 }
400 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800401 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800402 userData.account = accountName;
403 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800404 }
405 }
406
407 if (userToUpdate != null) {
408 writeUserLP(userToUpdate);
409 }
410 }
411 }
412
413 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700414 public UserInfo getPrimaryUser() {
415 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700416 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700417 final int userSize = mUsers.size();
418 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800419 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800420 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700421 return ui;
422 }
423 }
424 }
425 return null;
426 }
427
428 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700429 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700430 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700431 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700432 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700433 final int userSize = mUsers.size();
434 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800435 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700436 if (ui.partial) {
437 continue;
438 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800439 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700440 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700441 }
Amith Yamasani13593602012-03-22 16:16:17 -0700442 }
443 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700444 }
Amith Yamasani13593602012-03-22 16:16:17 -0700445 }
446
Amith Yamasani258848d2012-08-10 17:06:33 -0700447 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100448 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800449 if (userId != UserHandle.getCallingUserId()) {
450 checkManageUsersPermission("getting profiles related to user " + userId);
451 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700452 final long ident = Binder.clearCallingIdentity();
453 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700454 synchronized (mUsersLock) {
455 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100456 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700457 } finally {
458 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000459 }
460 }
461
Amith Yamasanibe465322014-04-24 13:45:17 -0700462 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700463 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
464 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700465 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700466 if (user == null) {
467 // Probably a dying user
468 return users;
469 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700470 final int userSize = mUsers.size();
471 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800472 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700473 if (!isProfileOf(user, profile)) {
474 continue;
475 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100476 if (enabledOnly && !profile.isEnabled()) {
477 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700478 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700479 if (mRemovingUserIds.get(profile.id)) {
480 continue;
481 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700482 users.add(profile);
483 }
484 return users;
485 }
486
Jessica Hummelbe81c802014-04-22 15:49:22 +0100487 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700488 public int getCredentialOwnerProfile(int userHandle) {
489 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000490 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700491 synchronized (mUsersLock) {
492 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700493 if (profileParent != null) {
494 return profileParent.id;
495 }
496 }
497 }
498
499 return userHandle;
500 }
501
502 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700503 public boolean isSameProfileGroup(int userId, int otherUserId) {
504 if (userId == otherUserId) return true;
505 checkManageUsersPermission("check if in the same profile group");
506 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700507 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700508 }
509 }
510
Fyodor Kupolov82402752015-10-28 14:54:51 -0700511 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
512 synchronized (mUsersLock) {
513 UserInfo userInfo = getUserInfoLU(userId);
514 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
515 return false;
516 }
517 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
518 if (otherUserInfo == null
519 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
520 return false;
521 }
522 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700523 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700524 }
525
526 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100527 public UserInfo getProfileParent(int userHandle) {
528 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700529 synchronized (mUsersLock) {
530 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700531 }
532 }
533
Fyodor Kupolov82402752015-10-28 14:54:51 -0700534 private UserInfo getProfileParentLU(int userHandle) {
535 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700536 if (profile == null) {
537 return null;
538 }
539 int parentUserId = profile.profileGroupId;
540 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
541 return null;
542 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700543 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100544 }
545 }
546
Fyodor Kupolov82402752015-10-28 14:54:51 -0700547 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100548 return user.id == profile.id ||
549 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
550 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000551 }
552
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000553 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
554 UserHandle parentHandle, Bundle extras) {
555 // Send intent to profile
556 Intent intent = new Intent(Intent.ACTION_AVAILABILITY_CHANGED);
557 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
558 intent.putExtras(extras);
559 mContext.sendBroadcastAsUser(intent, profileHandle);
560
561 // Send intent to parent
562 if (parentHandle != null) {
563 intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
564 intent.putExtra(Intent.EXTRA_USER, profileHandle);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700565 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000566 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
567 intent.putExtras(extras);
568 mContext.sendBroadcastAsUser(intent, parentHandle);
569 }
570 }
571
572 @Override
573 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
574 checkManageUsersPermission("silence profile");
575 boolean changed = false;
576 UserInfo profile, parent;
577 synchronized (mPackagesLock) {
578 synchronized (mUsersLock) {
579 profile = getUserInfoLU(userHandle);
580 parent = getProfileParentLU(userHandle);
581
582 }
583 if (profile == null || !profile.isManagedProfile()) {
584 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
585 }
586 if (profile.isQuietModeEnabled() != enableQuietMode) {
587 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800588 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000589 changed = true;
590 }
591 }
592 if (changed) {
593 Bundle extras = new Bundle();
594 extras.putBoolean(Intent.EXTRA_QUIET_MODE, enableQuietMode);
595 broadcastProfileAvailabilityChanges(profile.getUserHandle(),
596 parent != null ? parent.getUserHandle() : null, extras);
597 }
598 }
599
600 @Override
601 public boolean isQuietModeEnabled(int userHandle) {
602 synchronized (mPackagesLock) {
603 UserInfo info;
604 synchronized (mUsersLock) {
605 info = getUserInfoLU(userHandle);
606 }
607 if (info == null || !info.isManagedProfile()) {
608 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
609 }
610 return info.isQuietModeEnabled();
611 }
612 }
613
Kenny Guya52dc3e2014-02-11 15:33:14 +0000614 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100615 public void setUserEnabled(int userId) {
616 checkManageUsersPermission("enable user");
617 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700618 UserInfo info;
619 synchronized (mUsersLock) {
620 info = getUserInfoLU(userId);
621 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100622 if (info != null && !info.isEnabled()) {
623 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800624 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100625 }
626 }
627 }
628
629 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700630 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700631 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700632 synchronized (mUsersLock) {
633 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700634 }
635 }
636
Amith Yamasani71e6c692013-03-24 17:39:28 -0700637 @Override
638 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700639 synchronized (mUsersLock) {
640 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700641 }
642 }
643
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700644 @Override
645 public boolean canHaveRestrictedProfile(int userId) {
646 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700647 synchronized (mUsersLock) {
648 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700649 if (userInfo == null || !userInfo.canHaveProfile()) {
650 return false;
651 }
652 if (!userInfo.isAdmin()) {
653 return false;
654 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800655 // restricted profile can be created if there is no DO set and the admin user has no PO;
656 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700657 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700658 }
659
Amith Yamasani195263742012-08-21 15:40:12 -0700660 /*
661 * Should be locked on mUsers before calling this.
662 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700663 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800664 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700665 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800666 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700667 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
668 return null;
669 }
Amith Yamasani12747872015-12-07 14:19:49 -0800670 return userData != null ? userData.info : null;
671 }
672
673 private UserData getUserDataLU(int userId) {
674 final UserData userData = mUsers.get(userId);
675 // If it is partial and not in the process of being removed, return as unknown user.
676 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
677 return null;
678 }
679 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700680 }
681
Fyodor Kupolov82402752015-10-28 14:54:51 -0700682 /**
683 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
684 * <p>No permissions checking or any addition checks are made</p>
685 */
686 private UserInfo getUserInfoNoChecks(int userId) {
687 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800688 final UserData userData = mUsers.get(userId);
689 return userData != null ? userData.info : null;
690 }
691 }
692
693 /**
694 * Obtains {@link #mUsersLock} and return UserData from mUsers.
695 * <p>No permissions checking or any addition checks are made</p>
696 */
697 private UserData getUserDataNoChecks(int userId) {
698 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700699 return mUsers.get(userId);
700 }
701 }
702
Amith Yamasani236b2b52015-08-18 14:32:14 -0700703 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700704 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700705 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700706 }
707
Amith Yamasani258848d2012-08-10 17:06:33 -0700708 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700709 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700710 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700711 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700712 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800713 UserData userData = getUserDataNoChecks(userId);
714 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700715 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
716 return;
717 }
Amith Yamasani12747872015-12-07 14:19:49 -0800718 if (name != null && !name.equals(userData.info.name)) {
719 userData.info.name = name;
720 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700721 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700722 }
723 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700724 if (changed) {
725 sendUserInfoChangedBroadcast(userId);
726 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700727 }
728
Amith Yamasani258848d2012-08-10 17:06:33 -0700729 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700730 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700731 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100732 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
733 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
734 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700735 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100736 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700737 }
738
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100739
740
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700741 private void sendUserInfoChangedBroadcast(int userId) {
742 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
743 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
744 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700745 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700746 }
747
Amith Yamasani258848d2012-08-10 17:06:33 -0700748 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100749 public ParcelFileDescriptor getUserIcon(int userId) {
750 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700751 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700752 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700753 if (info == null || info.partial) {
754 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
755 return null;
756 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700757 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100758 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
759 || callingGroupId != info.profileGroupId) {
760 checkManageUsersPermission("get the icon of a user who is not related");
761 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700762 if (info.iconPath == null) {
763 return null;
764 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100765 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700766 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100767
768 try {
769 return ParcelFileDescriptor.open(
770 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
771 } catch (FileNotFoundException e) {
772 Log.e(LOG_TAG, "Couldn't find icon file", e);
773 }
774 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700775 }
776
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700777 public void makeInitialized(int userId) {
778 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800779 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800780 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800781 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800782 userData = mUsers.get(userId);
783 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700784 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800785 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700786 }
Amith Yamasani12747872015-12-07 14:19:49 -0800787 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
788 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800789 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700790 }
791 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800792 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800793 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800794 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700795 }
796
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700797 /**
798 * If default guest restrictions haven't been initialized yet, add the basic
799 * restrictions.
800 */
801 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800802 synchronized (mGuestRestrictions) {
803 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800804 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800805 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
806 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
807 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700808 }
809 }
810
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800811 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530812 public Bundle getDefaultGuestRestrictions() {
813 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800814 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530815 return new Bundle(mGuestRestrictions);
816 }
817 }
818
819 @Override
820 public void setDefaultGuestRestrictions(Bundle restrictions) {
821 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800822 synchronized (mGuestRestrictions) {
823 mGuestRestrictions.clear();
824 mGuestRestrictions.putAll(restrictions);
825 }
826 synchronized (mPackagesLock) {
827 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530828 }
829 }
830
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800831 /**
832 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
833 */
834 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
835 @Nullable Bundle global) {
836 Preconditions.checkNotNull(local);
837 boolean globalChanged = false;
838 boolean localChanged;
839 synchronized (mRestrictionsLock) {
840 if (global != null) {
841 // Update global.
842 globalChanged = !UserRestrictionsUtils.areEqual(
843 mDevicePolicyGlobalUserRestrictions, global);
844 if (globalChanged) {
845 mDevicePolicyGlobalUserRestrictions = global;
846 }
847 }
848 {
849 // Update local.
850 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
851 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
852 if (localChanged) {
853 mDevicePolicyLocalUserRestrictions.put(userId, local);
854 }
855 }
856 }
857 if (DBG) {
858 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
859 + " global=" + global + (globalChanged ? " (changed)" : "")
860 + " local=" + local + (localChanged ? " (changed)" : "")
861 );
862 }
863 // Don't call them within the mRestrictionsLock.
864 synchronized (mPackagesLock) {
865 if (globalChanged) {
866 writeUserListLP();
867 }
868 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800869 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800870 }
871 }
872
873 synchronized (mRestrictionsLock) {
874 if (globalChanged) {
875 applyUserRestrictionsForAllUsersLR();
876 } else if (localChanged) {
877 applyUserRestrictionsLR(userId);
878 }
879 }
880 }
881
Makoto Onuki068c54a2015-10-13 14:34:03 -0700882 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700883 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800884 final Bundle baseRestrictions =
885 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
886 final Bundle global = mDevicePolicyGlobalUserRestrictions;
887 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700888
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800889 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
890 // Common case first.
891 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700892 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800893 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
894 UserRestrictionsUtils.merge(effective, global);
895 UserRestrictionsUtils.merge(effective, local);
896
Makoto Onuki068c54a2015-10-13 14:34:03 -0700897 return effective;
898 }
899
900 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700901 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700902 if (DBG) {
903 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
904 }
905 mCachedEffectiveUserRestrictions.remove(userId);
906 }
907
908 private Bundle getEffectiveUserRestrictions(int userId) {
909 synchronized (mRestrictionsLock) {
910 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
911 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700912 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700913 mCachedEffectiveUserRestrictions.put(userId, restrictions);
914 }
915 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700916 }
917 }
918
Makoto Onuki068c54a2015-10-13 14:34:03 -0700919 /** @return a specific user restriction that's in effect currently. */
920 @Override
921 public boolean hasUserRestriction(String restrictionKey, int userId) {
922 Bundle restrictions = getEffectiveUserRestrictions(userId);
923 return restrictions != null && restrictions.getBoolean(restrictionKey);
924 }
925
926 /**
927 * @return UserRestrictions that are in effect currently. This always returns a new
928 * {@link Bundle}.
929 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700930 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800931 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800932 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800933 }
934
935 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000936 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
937 checkManageUsersPermission("hasBaseUserRestriction");
938 synchronized (mRestrictionsLock) {
939 Bundle bundle = mBaseUserRestrictions.get(userId);
940 return (bundle != null && bundle.getBoolean(restrictionKey, false));
941 }
942 }
943
944 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700945 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700946 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700947 synchronized (mRestrictionsLock) {
948 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
949 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800950 final Bundle newRestrictions = UserRestrictionsUtils.clone(
951 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700952 newRestrictions.putBoolean(key, value);
953
Fyodor Kupolov82402752015-10-28 14:54:51 -0700954 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700955 }
956 }
957
Makoto Onuki068c54a2015-10-13 14:34:03 -0700958 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800959 * Optionally updating user restrictions, calculate the effective user restrictions and also
960 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700961 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800962 * @param newRestrictions User restrictions to set.
963 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700964 * @param userId target user ID.
965 */
966 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700967 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700968 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800969
970 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
971 mAppliedUserRestrictions.get(userId));
972
973 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700974 if (newRestrictions != null) {
975 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800976 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
977
978 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700979 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
980 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800981
982 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
983 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -0800984 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800985 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700986 }
987
Fyodor Kupolov82402752015-10-28 14:54:51 -0700988 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700989
Makoto Onuki759a7632015-10-28 16:43:10 -0700990 mCachedEffectiveUserRestrictions.put(userId, effective);
991
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800992 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700993 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800994 debug("Applying user restrictions: userId=" + userId
995 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700996 }
997
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800998 if (mAppOpsService != null) { // We skip it until system-ready.
999 final long token = Binder.clearCallingIdentity();
1000 try {
1001 mAppOpsService.setUserRestrictions(effective, userId);
1002 } catch (RemoteException e) {
1003 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1004 } finally {
1005 Binder.restoreCallingIdentity(token);
1006 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001007 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001008
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001009 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001010
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001011 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001012 }
1013
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001014 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001015 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001016 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1017 // actually, but we still need some kind of synchronization otherwise we might end up
1018 // calling listeners out-of-order, thus "LR".
1019
1020 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1021 return;
1022 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001023
1024 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1025 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1026
1027 mHandler.post(new Runnable() {
1028 @Override
1029 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001030 UserRestrictionsUtils.applyUserRestrictions(
1031 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001032
Makoto Onukid45a4a22015-11-02 17:17:38 -08001033 final UserRestrictionsListener[] listeners;
1034 synchronized (mUserRestrictionsListeners) {
1035 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1036 mUserRestrictionsListeners.toArray(listeners);
1037 }
1038 for (int i = 0; i < listeners.length; i++) {
1039 listeners[i].onUserRestrictionsChanged(userId,
1040 newRestrictionsFinal, prevRestrictionsFinal);
1041 }
1042 }
1043 });
1044 }
1045
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001046 // Package private for the inner class.
1047 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001048 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001049 }
1050
1051 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001052 // Package private for the inner class.
1053 void applyUserRestrictionsForAllUsersLR() {
1054 if (DBG) {
1055 debug("applyUserRestrictionsForAllUsersLR");
1056 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001057 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001058 mCachedEffectiveUserRestrictions.clear();
1059
Makoto Onuki068c54a2015-10-13 14:34:03 -07001060 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1061 // it on a handler.
1062 final Runnable r = new Runnable() {
1063 @Override
1064 public void run() {
1065 // Then get the list of running users.
1066 final int[] runningUsers;
1067 try {
1068 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1069 } catch (RemoteException e) {
1070 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1071 return;
1072 }
1073 // Then re-calculate the effective restrictions and apply, only for running users.
1074 // It's okay if a new user has started after the getRunningUserIds() call,
1075 // because we'll do the same thing (re-calculate the restrictions and apply)
1076 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001077 synchronized (mRestrictionsLock) {
1078 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001079 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001080 }
1081 }
1082 }
1083 };
1084 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001085 }
1086
Amith Yamasani258848d2012-08-10 17:06:33 -07001087 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001088 * Check if we've hit the limit of how many users can be created.
1089 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001090 private boolean isUserLimitReached() {
1091 int count;
1092 synchronized (mUsersLock) {
1093 count = getAliveUsersExcludingGuestsCountLU();
1094 }
1095 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001096 }
1097
1098 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001099 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001100 checkManageUsersPermission("check if more managed profiles can be added.");
1101 if (ActivityManager.isLowRamDeviceStatic()) {
1102 return false;
1103 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001104 if (!mContext.getPackageManager().hasSystemFeature(
1105 PackageManager.FEATURE_MANAGED_USERS)) {
1106 return false;
1107 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001108 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001109 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1110 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1111 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001112 return false;
1113 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001114 synchronized(mUsersLock) {
1115 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001116 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001117 return false;
1118 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001119 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1120 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001121 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001122 return usersCountAfterRemoving == 1
1123 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001124 }
1125 }
1126
Fyodor Kupolov82402752015-10-28 14:54:51 -07001127 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001128 int aliveUserCount = 0;
1129 final int totalUserCount = mUsers.size();
1130 // Skip over users being removed
1131 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001132 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001133 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001134 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001135 aliveUserCount++;
1136 }
1137 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001138 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001139 }
1140
1141 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001142 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001143 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1144 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1145 * permissions can make certain calls to the UserManager.
1146 *
1147 * @param message used as message if SecurityException is thrown
1148 * @throws SecurityException if the caller does not have enough privilege.
1149 */
1150 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1151 final int uid = Binder.getCallingUid();
1152 if (uid != Process.SYSTEM_UID && uid != 0
1153 && ActivityManager.checkComponentPermission(
1154 Manifest.permission.MANAGE_USERS,
1155 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1156 && ActivityManager.checkComponentPermission(
1157 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1158 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1159 throw new SecurityException(
1160 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1161 + message);
1162 }
1163 }
1164
1165 /**
1166 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001167 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001168 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001169 *
1170 * @param message used as message if SecurityException is thrown
1171 * @throws SecurityException if the caller is not system or root
1172 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001173 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001174 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001175 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001176 && ActivityManager.checkComponentPermission(
1177 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001178 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1179 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1180 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001181 }
1182
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001183 /**
1184 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1185 * UserManager.
1186 *
1187 * @param message used as message if SecurityException is thrown
1188 * @throws SecurityException if the caller is not system or root
1189 */
1190 private static void checkSystemOrRoot(String message) {
1191 final int uid = Binder.getCallingUid();
1192 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1193 throw new SecurityException("Only system may: " + message);
1194 }
1195 }
1196
Fyodor Kupolov82402752015-10-28 14:54:51 -07001197 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001198 try {
1199 File dir = new File(mUsersDir, Integer.toString(info.id));
1200 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001201 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001202 if (!dir.exists()) {
1203 dir.mkdir();
1204 FileUtils.setPermissions(
1205 dir.getPath(),
1206 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1207 -1, -1);
1208 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001209 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001210 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1211 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001212 info.iconPath = file.getAbsolutePath();
1213 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001214 try {
1215 os.close();
1216 } catch (IOException ioe) {
1217 // What the ... !
1218 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001219 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001220 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001221 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001222 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001223 }
1224
Amith Yamasani0b285492011-04-14 17:35:23 -07001225 /**
1226 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1227 * cache it elsewhere.
1228 * @return the array of user ids.
1229 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001230 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001231 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001232 return mUserIds;
1233 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001234 }
1235
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001236 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001237 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001238 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001239 return;
1240 }
1241 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001242 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001243 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001244 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001245 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001246 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001247 int type;
1248 while ((type = parser.next()) != XmlPullParser.START_TAG
1249 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001250 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001251 }
1252
1253 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001254 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001255 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001256 return;
1257 }
1258
Amith Yamasani2a003292012-08-14 18:25:45 -07001259 mNextSerialNumber = -1;
1260 if (parser.getName().equals(TAG_USERS)) {
1261 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1262 if (lastSerialNumber != null) {
1263 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1264 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001265 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1266 if (versionNumber != null) {
1267 mUserVersion = Integer.parseInt(versionNumber);
1268 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001269 }
1270
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001271 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1272
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001273 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301274 if (type == XmlPullParser.START_TAG) {
1275 final String name = parser.getName();
1276 if (name.equals(TAG_USER)) {
1277 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001278
Amith Yamasani12747872015-12-07 14:19:49 -08001279 UserData userData = readUserLP(Integer.parseInt(id));
1280
1281 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001282 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001283 mUsers.put(userData.info.id, userData);
1284 if (mNextSerialNumber < 0
1285 || mNextSerialNumber <= userData.info.id) {
1286 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001287 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301288 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001289 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301290 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001291 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1292 && type != XmlPullParser.END_TAG) {
1293 if (type == XmlPullParser.START_TAG) {
1294 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001295 synchronized (mGuestRestrictions) {
1296 UserRestrictionsUtils
1297 .readRestrictions(parser, mGuestRestrictions);
1298 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001299 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1300 ) {
1301 UserRestrictionsUtils.readRestrictions(parser,
1302 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001303 }
1304 break;
1305 }
1306 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001307 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001308 }
1309 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001310 synchronized (mRestrictionsLock) {
1311 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1312 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001313 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001314 upgradeIfNecessaryLP();
1315 } catch (IOException | XmlPullParserException e) {
1316 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001317 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001318 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001319 }
1320 }
1321
Amith Yamasani6f34b412012-10-22 18:19:27 -07001322 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001323 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001324 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001325 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001326 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001327 int userVersion = mUserVersion;
1328 if (userVersion < 1) {
1329 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001330 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1331 if ("Primary".equals(userData.info.name)) {
1332 userData.info.name =
1333 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1334 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001335 }
1336 userVersion = 1;
1337 }
1338
Amith Yamasanibc9625052012-11-15 14:39:18 -08001339 if (userVersion < 2) {
1340 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001341 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1342 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1343 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1344 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001345 }
1346 userVersion = 2;
1347 }
1348
Amith Yamasani350962c2013-08-06 11:18:53 -07001349
Amith Yamasani5e486f52013-08-07 11:06:44 -07001350 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001351 userVersion = 4;
1352 }
1353
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001354 if (userVersion < 5) {
1355 initDefaultGuestRestrictions();
1356 userVersion = 5;
1357 }
1358
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001359 if (userVersion < 6) {
1360 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001361 synchronized (mUsersLock) {
1362 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001363 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001364 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001365 if (!splitSystemUser && userData.info.isRestricted()
1366 && (userData.info.restrictedProfileParentId
1367 == UserInfo.NO_PROFILE_GROUP_ID)) {
1368 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1369 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001370 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001371 }
1372 }
1373 userVersion = 6;
1374 }
1375
Amith Yamasani6f34b412012-10-22 18:19:27 -07001376 if (userVersion < USER_VERSION) {
1377 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1378 + USER_VERSION);
1379 } else {
1380 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001381
1382 if (originalVersion < mUserVersion) {
1383 writeUserListLP();
1384 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001385 }
1386 }
1387
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001388 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001389 int flags = UserInfo.FLAG_INITIALIZED;
1390 // In split system user mode, the admin and primary flags are assigned to the first human
1391 // user.
1392 if (!UserManager.isSplitSystemUser()) {
1393 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1394 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001395 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001396 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001397 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001398 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001399 UserData userData = new UserData();
1400 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001401 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001402 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001403 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001404 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001405 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001406
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001407 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001408 synchronized (mRestrictionsLock) {
1409 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1410 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001411
Fyodor Kupolov82402752015-10-28 14:54:51 -07001412 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001413 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001414
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001415 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001416 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001417 }
1418
Amith Yamasani12747872015-12-07 14:19:49 -08001419 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001420 if (DBG) {
1421 debug("scheduleWriteUser");
1422 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001423 // No need to wrap it within a lock -- worst case, we'll just post the same message
1424 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001425 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1426 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001427 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1428 }
1429 }
1430
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001431 /*
1432 * Writes the user file in this format:
1433 *
1434 * <user flags="20039023" id="0">
1435 * <name>Primary</name>
1436 * </user>
1437 */
Amith Yamasani12747872015-12-07 14:19:49 -08001438 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001439 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001440 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001441 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001442 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001443 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001444 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001445 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001446 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1447
1448 // XmlSerializer serializer = XmlUtils.serializerInstance();
1449 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001450 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001451 serializer.startDocument(null, true);
1452 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1453
Amith Yamasani12747872015-12-07 14:19:49 -08001454 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001455 serializer.startTag(null, TAG_USER);
1456 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001457 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001458 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001459 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1460 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1461 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001462 if (userInfo.iconPath != null) {
1463 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1464 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001465 if (userInfo.partial) {
1466 serializer.attribute(null, ATTR_PARTIAL, "true");
1467 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001468 if (userInfo.guestToRemove) {
1469 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1470 }
Kenny Guy2a764942014-04-02 13:29:20 +01001471 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1472 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1473 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001474 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001475 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1476 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1477 Integer.toString(userInfo.restrictedProfileParentId));
1478 }
Amith Yamasani12747872015-12-07 14:19:49 -08001479 // Write seed data
1480 if (userData.persistSeedData) {
1481 if (userData.seedAccountName != null) {
1482 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1483 }
1484 if (userData.seedAccountType != null) {
1485 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1486 }
1487 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001488 serializer.startTag(null, TAG_NAME);
1489 serializer.text(userInfo.name);
1490 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001491 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001492 UserRestrictionsUtils.writeRestrictions(serializer,
1493 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1494 UserRestrictionsUtils.writeRestrictions(serializer,
1495 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1496 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001497 }
Amith Yamasani12747872015-12-07 14:19:49 -08001498
1499 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001500 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001501 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001502 serializer.endTag(null, TAG_ACCOUNT);
1503 }
1504
Amith Yamasani12747872015-12-07 14:19:49 -08001505 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1506 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1507 userData.seedAccountOptions.saveToXml(serializer);
1508 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1509 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001510 serializer.endTag(null, TAG_USER);
1511
1512 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001513 userFile.finishWrite(fos);
1514 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001515 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001516 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001517 }
1518 }
1519
1520 /*
1521 * Writes the user list file in this format:
1522 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001523 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001524 * <user id="0"></user>
1525 * <user id="2"></user>
1526 * </users>
1527 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001528 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001529 if (DBG) {
1530 debug("writeUserList");
1531 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001532 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001533 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001534 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001535 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001536 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1537
1538 // XmlSerializer serializer = XmlUtils.serializerInstance();
1539 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001540 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001541 serializer.startDocument(null, true);
1542 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1543
1544 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001545 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001546 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001547
Adam Lesinskieddeb492014-09-08 17:50:03 -07001548 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001549 synchronized (mGuestRestrictions) {
1550 UserRestrictionsUtils
1551 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1552 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301553 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001554 synchronized (mRestrictionsLock) {
1555 UserRestrictionsUtils.writeRestrictions(serializer,
1556 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1557 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001558 int[] userIdsToWrite;
1559 synchronized (mUsersLock) {
1560 userIdsToWrite = new int[mUsers.size()];
1561 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001562 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001563 userIdsToWrite[i] = user.id;
1564 }
1565 }
1566 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001567 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001568 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001569 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001570 }
1571
1572 serializer.endTag(null, TAG_USERS);
1573
1574 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001575 userListFile.finishWrite(fos);
1576 } catch (Exception e) {
1577 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001578 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001579 }
1580 }
1581
Amith Yamasani12747872015-12-07 14:19:49 -08001582 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001583 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001584 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001585 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001586 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001587 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001588 long creationTime = 0L;
1589 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001590 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001591 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001592 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001593 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001594 boolean persistSeedData = false;
1595 String seedAccountName = null;
1596 String seedAccountType = null;
1597 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001598 Bundle baseRestrictions = new Bundle();
1599 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001600
1601 FileInputStream fis = null;
1602 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001603 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001604 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001605 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001606 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001607 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001608 int type;
1609 while ((type = parser.next()) != XmlPullParser.START_TAG
1610 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001611 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001612 }
1613
1614 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001615 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001616 return null;
1617 }
1618
1619 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001620 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1621 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001622 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001623 return null;
1624 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001625 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1626 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001627 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001628 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1629 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001630 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1631 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001632 restrictedProfileParentId = readIntAttribute(parser,
1633 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001634 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1635 if ("true".equals(valueString)) {
1636 partial = true;
1637 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001638 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1639 if ("true".equals(valueString)) {
1640 guestToRemove = true;
1641 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001642
Amith Yamasani12747872015-12-07 14:19:49 -08001643 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1644 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1645 if (seedAccountName != null || seedAccountType != null) {
1646 persistSeedData = true;
1647 }
1648
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001649 int outerDepth = parser.getDepth();
1650 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1651 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1652 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1653 continue;
1654 }
1655 String tag = parser.getName();
1656 if (TAG_NAME.equals(tag)) {
1657 type = parser.next();
1658 if (type == XmlPullParser.TEXT) {
1659 name = parser.getText();
1660 }
1661 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001662 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1663 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1664 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001665 } else if (TAG_ACCOUNT.equals(tag)) {
1666 type = parser.next();
1667 if (type == XmlPullParser.TEXT) {
1668 account = parser.getText();
1669 }
Amith Yamasani12747872015-12-07 14:19:49 -08001670 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1671 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1672 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001673 }
1674 }
1675 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001676
Amith Yamasani12747872015-12-07 14:19:49 -08001677 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001678 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001679 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001680 userInfo.creationTime = creationTime;
1681 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001682 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001683 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001684 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001685 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001686
1687 // Create the UserData object that's internal to this class
1688 UserData userData = new UserData();
1689 userData.info = userInfo;
1690 userData.account = account;
1691 userData.seedAccountName = seedAccountName;
1692 userData.seedAccountType = seedAccountType;
1693 userData.persistSeedData = persistSeedData;
1694 userData.seedAccountOptions = seedAccountOptions;
1695
Makoto Onuki068c54a2015-10-13 14:34:03 -07001696 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001697 mBaseUserRestrictions.put(id, baseRestrictions);
1698 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001699 }
Amith Yamasani12747872015-12-07 14:19:49 -08001700 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001701 } catch (IOException ioe) {
1702 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001703 } finally {
1704 if (fis != null) {
1705 try {
1706 fis.close();
1707 } catch (IOException e) {
1708 }
1709 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001710 }
1711 return null;
1712 }
1713
Amith Yamasani920ace02012-09-20 22:15:37 -07001714 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1715 String valueString = parser.getAttributeValue(null, attr);
1716 if (valueString == null) return defaultValue;
1717 try {
1718 return Integer.parseInt(valueString);
1719 } catch (NumberFormatException nfe) {
1720 return defaultValue;
1721 }
1722 }
1723
1724 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1725 String valueString = parser.getAttributeValue(null, attr);
1726 if (valueString == null) return defaultValue;
1727 try {
1728 return Long.parseLong(valueString);
1729 } catch (NumberFormatException nfe) {
1730 return defaultValue;
1731 }
1732 }
1733
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001734 private boolean isPackageInstalled(String pkg, int userId) {
1735 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1736 PackageManager.GET_UNINSTALLED_PACKAGES,
1737 userId);
1738 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1739 return false;
1740 }
1741 return true;
1742 }
1743
Amith Yamasanib82add22013-07-09 11:24:44 -07001744 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001745 * Removes the app restrictions file for a specific package and user id, if it exists.
1746 */
1747 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1748 synchronized (mPackagesLock) {
1749 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001750 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001751 if (resFile.exists()) {
1752 resFile.delete();
1753 }
1754 }
1755 }
1756
Kenny Guya52dc3e2014-02-11 15:33:14 +00001757 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001758 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001759 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001760 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001761 }
1762
Amith Yamasani258848d2012-08-10 17:06:33 -07001763 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001764 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001765 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001766 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001767 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001768
Jessica Hummelbe81c802014-04-22 15:49:22 +01001769 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001770 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001771 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1772 return null;
1773 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001774 if (ActivityManager.isLowRamDeviceStatic()) {
1775 return null;
1776 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001777 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001778 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001779 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001780 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001781 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001782 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001783 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001784 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001785 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001786 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001787 if (parentId != UserHandle.USER_NULL) {
1788 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001789 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001790 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001791 if (parent == null) return null;
1792 }
1793 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1794 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1795 return null;
1796 }
1797 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1798 // If we're not adding a guest user or a managed profile and the limit has
1799 // been reached, cannot add a user.
1800 return null;
1801 }
1802 // If we're adding a guest and there already exists one, bail.
1803 if (isGuest && findCurrentGuestUser() != null) {
1804 return null;
1805 }
1806 // In legacy mode, restricted profile's parent can only be the owner user
1807 if (isRestricted && !UserManager.isSplitSystemUser()
1808 && (parentId != UserHandle.USER_SYSTEM)) {
1809 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1810 return null;
1811 }
1812 if (isRestricted && UserManager.isSplitSystemUser()) {
1813 if (parent == null) {
1814 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1815 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001816 return null;
1817 }
Amith Yamasani12747872015-12-07 14:19:49 -08001818 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001819 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1820 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001821 return null;
1822 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001823 }
1824 // In split system user mode, we assign the first human user the primary flag.
1825 // And if there is no device owner, we also assign the admin flag to primary user.
1826 if (UserManager.isSplitSystemUser()
1827 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1828 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001829 synchronized (mUsersLock) {
1830 if (!mIsDeviceManaged) {
1831 flags |= UserInfo.FLAG_ADMIN;
1832 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001833 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001834 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001835
Amith Yamasani12747872015-12-07 14:19:49 -08001836 if (parent != null && parent.info.isEphemeral()) {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001837 flags |= UserInfo.FLAG_EPHEMERAL;
1838 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001839 userId = getNextAvailableId();
1840 userInfo = new UserInfo(userId, name, null, flags);
1841 userInfo.serialNumber = mNextSerialNumber++;
1842 long now = System.currentTimeMillis();
1843 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1844 userInfo.partial = true;
Amith Yamasani12747872015-12-07 14:19:49 -08001845 userData = new UserData();
1846 userData.info = userInfo;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001847 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1848 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001849 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001850 }
1851 writeUserListLP();
1852 if (parent != null) {
1853 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001854 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1855 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001856 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001857 }
Amith Yamasani12747872015-12-07 14:19:49 -08001858 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001859 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001860 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1861 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001862 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001863 }
Amith Yamasani12747872015-12-07 14:19:49 -08001864 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001865 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001866 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001867 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001868 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001869 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001870 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1871 final String volumeUuid = vol.getFsUuid();
1872 try {
1873 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001874 storage.prepareUserStorage(
1875 volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001876 enforceSerialNumber(userDir, userInfo.serialNumber);
1877 } catch (IOException e) {
1878 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1879 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001880 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001881 mPm.createNewUser(userId);
1882 userInfo.partial = false;
1883 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001884 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001885 }
1886 updateUserIds();
1887 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001888 if (isGuest) {
1889 synchronized (mGuestRestrictions) {
1890 restrictions.putAll(mGuestRestrictions);
1891 }
1892 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001893 synchronized (mRestrictionsLock) {
1894 mBaseUserRestrictions.append(userId, restrictions);
1895 }
1896 mPm.newUserCreated(userId);
1897 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1898 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1899 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1900 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001901 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001902 } finally {
1903 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001904 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001905 return userInfo;
1906 }
1907
Amith Yamasani0b285492011-04-14 17:35:23 -07001908 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001909 * @hide
1910 */
Amith Yamasani12747872015-12-07 14:19:49 -08001911 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001912 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1913 checkManageUsersPermission("setupRestrictedProfile");
1914 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1915 if (user == null) {
1916 return null;
1917 }
1918 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1919 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1920 // the putIntForUser() will fail.
1921 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1922 android.provider.Settings.Secure.LOCATION_MODE,
1923 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1924 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1925 return user;
1926 }
1927
1928 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001929 * Find the current guest user. If the Guest user is partial,
1930 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001931 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001932 private UserInfo findCurrentGuestUser() {
1933 synchronized (mUsersLock) {
1934 final int size = mUsers.size();
1935 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001936 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001937 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1938 return user;
1939 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001940 }
1941 }
1942 return null;
1943 }
1944
1945 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001946 * Mark this guest user for deletion to allow us to create another guest
1947 * and switch to that user before actually removing this guest.
1948 * @param userHandle the userid of the current guest
1949 * @return whether the user could be marked for deletion
1950 */
Amith Yamasani12747872015-12-07 14:19:49 -08001951 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07001952 public boolean markGuestForDeletion(int userHandle) {
1953 checkManageUsersPermission("Only the system can remove users");
1954 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1955 UserManager.DISALLOW_REMOVE_USER, false)) {
1956 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1957 return false;
1958 }
1959
1960 long ident = Binder.clearCallingIdentity();
1961 try {
Amith Yamasani12747872015-12-07 14:19:49 -08001962 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07001963 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001964 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001965 userData = mUsers.get(userHandle);
1966 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001967 return false;
1968 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001969 }
Amith Yamasani12747872015-12-07 14:19:49 -08001970 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07001971 return false;
1972 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001973 // We set this to a guest user that is to be removed. This is a temporary state
1974 // where we are allowed to add new Guest users, even if this one is still not
1975 // removed. This user will still show up in getUserInfo() calls.
1976 // If we don't get around to removing this Guest user, it will be purged on next
1977 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08001978 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001979 // Mark it as disabled, so that it isn't returned any more when
1980 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08001981 userData.info.flags |= UserInfo.FLAG_DISABLED;
1982 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07001983 }
1984 } finally {
1985 Binder.restoreCallingIdentity(ident);
1986 }
1987 return true;
1988 }
1989
1990 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001991 * Removes a user and all data directories created for that user. This method should be called
1992 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001993 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001994 */
Amith Yamasani12747872015-12-07 14:19:49 -08001995 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07001996 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001997 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001998 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1999 UserManager.DISALLOW_REMOVE_USER, false)) {
2000 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2001 return false;
2002 }
2003
Kenny Guyee58b4f2014-05-23 15:19:53 +01002004 long ident = Binder.clearCallingIdentity();
2005 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002006 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002007 int currentUser = ActivityManager.getCurrentUser();
2008 if (currentUser == userHandle) {
2009 Log.w(LOG_TAG, "Current user cannot be removed");
2010 return false;
2011 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002012 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002013 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002014 userData = mUsers.get(userHandle);
2015 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002016 return false;
2017 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002018
Fyodor Kupolov82402752015-10-28 14:54:51 -07002019 // We remember deleted user IDs to prevent them from being
2020 // reused during the current boot; they can still be reused
2021 // after a reboot.
2022 mRemovingUserIds.put(userHandle, true);
2023 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002024
Kenny Guyee58b4f2014-05-23 15:19:53 +01002025 try {
2026 mAppOpsService.removeUser(userHandle);
2027 } catch (RemoteException e) {
2028 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2029 }
2030 // Set this to a partially created user, so that the user will be purged
2031 // on next startup, in case the runtime stops now before stopping and
2032 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002033 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002034 // Mark it as disabled, so that it isn't returned any more when
2035 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002036 userData.info.flags |= UserInfo.FLAG_DISABLED;
2037 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002038 }
2039
Amith Yamasani12747872015-12-07 14:19:49 -08002040 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2041 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002042 // Send broadcast to notify system that the user removed was a
2043 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002044 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002045 }
2046
2047 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2048 int res;
2049 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002050 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2051 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002052 @Override
2053 public void userStopped(int userId) {
2054 finishRemoveUser(userId);
2055 }
2056 @Override
2057 public void userStopAborted(int userId) {
2058 }
2059 });
2060 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002061 return false;
2062 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002063 return res == ActivityManager.USER_OP_SUCCESS;
2064 } finally {
2065 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002066 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002067 }
2068
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002069 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002070 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002071 // Let other services shutdown any activity and clean up their state before completely
2072 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002073 long ident = Binder.clearCallingIdentity();
2074 try {
2075 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2076 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002077 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2078 android.Manifest.permission.MANAGE_USERS,
2079
2080 new BroadcastReceiver() {
2081 @Override
2082 public void onReceive(Context context, Intent intent) {
2083 if (DBG) {
2084 Slog.i(LOG_TAG,
2085 "USER_REMOVED broadcast sent, cleaning up user data "
2086 + userHandle);
2087 }
2088 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002089 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002090 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002091 // Clean up any ActivityManager state
2092 LocalServices.getService(ActivityManagerInternal.class)
2093 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002094 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002095 }
2096 }.start();
2097 }
2098 },
2099
2100 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002101 } finally {
2102 Binder.restoreCallingIdentity(ident);
2103 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002104 }
2105
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002106 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002107 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002108 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002109 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002110
2111 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002112 synchronized (mUsersLock) {
2113 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002114 mIsUserManaged.delete(userHandle);
2115 }
2116 synchronized (mRestrictionsLock) {
2117 mBaseUserRestrictions.remove(userHandle);
2118 mAppliedUserRestrictions.remove(userHandle);
2119 mCachedEffectiveUserRestrictions.remove(userHandle);
2120 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002121 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002122 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002123 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002124 userFile.delete();
2125 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002126 synchronized (mPackagesLock) {
2127 writeUserListLP();
2128 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002129 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002130 File userDir = Environment.getUserSystemDirectory(userHandle);
2131 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2132 if (userDir.renameTo(renamedUserDir)) {
2133 removeDirectoryRecursive(renamedUserDir);
2134 } else {
2135 removeDirectoryRecursive(userDir);
2136 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002137 }
2138
Amith Yamasani61f57372012-08-31 12:12:28 -07002139 private void removeDirectoryRecursive(File parent) {
2140 if (parent.isDirectory()) {
2141 String[] files = parent.list();
2142 for (String filename : files) {
2143 File child = new File(parent, filename);
2144 removeDirectoryRecursive(child);
2145 }
2146 }
2147 parent.delete();
2148 }
2149
Kenny Guyf8d3a232014-05-15 16:09:52 +01002150 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002151 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002152 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2153 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002154 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002155 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002156 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002157 }
2158
Amith Yamasani2a003292012-08-14 18:25:45 -07002159 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002160 public Bundle getApplicationRestrictions(String packageName) {
2161 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2162 }
2163
2164 @Override
2165 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002166 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002167 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002168 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002169 }
2170 synchronized (mPackagesLock) {
2171 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002172 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002173 }
2174 }
2175
2176 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002177 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002178 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002179 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002180 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002181 if (restrictions == null || restrictions.isEmpty()) {
2182 cleanAppRestrictionsForPackage(packageName, userId);
2183 } else {
2184 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002185 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002186 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002187 }
Robin Lee66e5d962014-04-09 16:44:21 +01002188
Kenny Guyd21b2182014-07-17 16:38:55 +01002189 if (isPackageInstalled(packageName, userId)) {
2190 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2191 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2192 changeIntent.setPackage(packageName);
2193 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2194 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2195 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002196 }
2197
2198 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002199 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002200 try {
2201 return mContext.getPackageManager().getApplicationInfo(packageName,
2202 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2203 } catch (NameNotFoundException nnfe) {
2204 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002205 } finally {
2206 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002207 }
2208 }
2209
Fyodor Kupolov82402752015-10-28 14:54:51 -07002210 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002211 AtomicFile restrictionsFile =
2212 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2213 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002214 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002215 }
2216
2217 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002218 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002219 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002220 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002221 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002222 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002223 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002224
2225 FileInputStream fis = null;
2226 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002227 fis = restrictionsFile.openRead();
2228 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002229 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002230 XmlUtils.nextElement(parser);
2231 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002232 Slog.e(LOG_TAG, "Unable to read restrictions file "
2233 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002234 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002235 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002236 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2237 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002238 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002239 } catch (IOException|XmlPullParserException e) {
2240 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002241 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002242 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002243 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002244 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002245 }
2246
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002247 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2248 XmlPullParser parser) throws XmlPullParserException, IOException {
2249 int type = parser.getEventType();
2250 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2251 String key = parser.getAttributeValue(null, ATTR_KEY);
2252 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2253 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2254 if (multiple != null) {
2255 values.clear();
2256 int count = Integer.parseInt(multiple);
2257 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2258 if (type == XmlPullParser.START_TAG
2259 && parser.getName().equals(TAG_VALUE)) {
2260 values.add(parser.nextText().trim());
2261 count--;
2262 }
2263 }
2264 String [] valueStrings = new String[values.size()];
2265 values.toArray(valueStrings);
2266 restrictions.putStringArray(key, valueStrings);
2267 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2268 restrictions.putBundle(key, readBundleEntry(parser, values));
2269 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2270 final int outerDepth = parser.getDepth();
2271 ArrayList<Bundle> bundleList = new ArrayList<>();
2272 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2273 Bundle childBundle = readBundleEntry(parser, values);
2274 bundleList.add(childBundle);
2275 }
2276 restrictions.putParcelableArray(key,
2277 bundleList.toArray(new Bundle[bundleList.size()]));
2278 } else {
2279 String value = parser.nextText().trim();
2280 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2281 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2282 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2283 restrictions.putInt(key, Integer.parseInt(value));
2284 } else {
2285 restrictions.putString(key, value);
2286 }
2287 }
2288 }
2289 }
2290
2291 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2292 throws IOException, XmlPullParserException {
2293 Bundle childBundle = new Bundle();
2294 final int outerDepth = parser.getDepth();
2295 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2296 readEntry(childBundle, values, parser);
2297 }
2298 return childBundle;
2299 }
2300
Fyodor Kupolov82402752015-10-28 14:54:51 -07002301 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002302 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002303 AtomicFile restrictionsFile = new AtomicFile(
2304 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002305 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002306 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002307 }
2308
2309 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002310 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002311 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002312 try {
2313 fos = restrictionsFile.startWrite();
2314 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2315
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002316 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002317 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002318 serializer.startDocument(null, true);
2319 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2320
2321 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002322 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002323 serializer.endTag(null, TAG_RESTRICTIONS);
2324
2325 serializer.endDocument();
2326 restrictionsFile.finishWrite(fos);
2327 } catch (Exception e) {
2328 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002329 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2330 }
2331 }
2332
2333 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2334 throws IOException {
2335 for (String key : restrictions.keySet()) {
2336 Object value = restrictions.get(key);
2337 serializer.startTag(null, TAG_ENTRY);
2338 serializer.attribute(null, ATTR_KEY, key);
2339
2340 if (value instanceof Boolean) {
2341 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2342 serializer.text(value.toString());
2343 } else if (value instanceof Integer) {
2344 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2345 serializer.text(value.toString());
2346 } else if (value == null || value instanceof String) {
2347 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2348 serializer.text(value != null ? (String) value : "");
2349 } else if (value instanceof Bundle) {
2350 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2351 writeBundle((Bundle) value, serializer);
2352 } else if (value instanceof Parcelable[]) {
2353 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2354 Parcelable[] array = (Parcelable[]) value;
2355 for (Parcelable parcelable : array) {
2356 if (!(parcelable instanceof Bundle)) {
2357 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2358 }
2359 serializer.startTag(null, TAG_ENTRY);
2360 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2361 writeBundle((Bundle) parcelable, serializer);
2362 serializer.endTag(null, TAG_ENTRY);
2363 }
2364 } else {
2365 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2366 String[] values = (String[]) value;
2367 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2368 for (String choice : values) {
2369 serializer.startTag(null, TAG_VALUE);
2370 serializer.text(choice != null ? choice : "");
2371 serializer.endTag(null, TAG_VALUE);
2372 }
2373 }
2374 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002375 }
2376 }
2377
2378 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002379 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002380 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002381 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002382 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002383 }
2384 }
2385
2386 @Override
2387 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002388 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002389 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002390 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002391 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002392 }
2393 // Not found
2394 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002395 }
2396 }
2397
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002398 @Override
2399 public long getUserCreationTime(int userHandle) {
2400 int callingUserId = UserHandle.getCallingUserId();
2401 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002402 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002403 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002404 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002405 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002406 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002407 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002408 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002409 }
2410 }
2411 }
2412 if (userInfo == null) {
2413 throw new SecurityException("userHandle can only be the calling user or a managed "
2414 + "profile associated with this user");
2415 }
2416 return userInfo.creationTime;
2417 }
2418
Amith Yamasani0b285492011-04-14 17:35:23 -07002419 /**
2420 * Caches the list of user ids in an array, adjusting the array size when necessary.
2421 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002422 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002423 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002424 synchronized (mUsersLock) {
2425 final int userSize = mUsers.size();
2426 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002427 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002428 num++;
2429 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002430 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002431 final int[] newUsers = new int[num];
2432 int n = 0;
2433 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002434 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002435 newUsers[n++] = mUsers.keyAt(i);
2436 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002437 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002438 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002439 }
2440 }
2441
2442 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002443 * Called right before a user is started. This gives us a chance to prepare
2444 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002445 */
2446 public void onBeforeStartUser(int userId) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002447 mPm.reconcileAppsData(userId, Installer.FLAG_DE_STORAGE);
2448
2449 if (userId != UserHandle.USER_SYSTEM) {
2450 synchronized (mRestrictionsLock) {
2451 applyUserRestrictionsLR(userId);
2452 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002453 }
2454 }
2455
2456 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002457 * Called right before a user is unlocked. This gives us a chance to prepare
2458 * app storage.
2459 */
2460 public void onBeforeUnlockUser(int userId) {
2461 mPm.reconcileAppsData(userId, Installer.FLAG_CE_STORAGE);
2462 }
2463
2464 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002465 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002466 * @param userId the user that was just foregrounded
2467 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002468 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002469 UserData userData = getUserDataNoChecks(userId);
2470 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002471 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2472 return;
2473 }
2474 long now = System.currentTimeMillis();
2475 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002476 userData.info.lastLoggedInTime = now;
2477 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002478 }
2479 }
2480
2481 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002482 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002483 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2484 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002485 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002486 private int getNextAvailableId() {
2487 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002488 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002489 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002490 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002491 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002492 }
2493 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002494 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002495 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002496 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002497 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002498
Amith Yamasanifc95e702013-09-26 13:20:17 -07002499 private String packageToRestrictionsFileName(String packageName) {
2500 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2501 }
2502
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002503 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002504 * Enforce that serial number stored in user directory inode matches the
2505 * given expected value. Gracefully sets the serial number if currently
2506 * undefined.
2507 *
2508 * @throws IOException when problem extracting serial number, or serial
2509 * number is mismatched.
2510 */
2511 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2512 final int foundSerial = getSerialNumber(file);
2513 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2514
2515 if (foundSerial == -1) {
2516 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2517 try {
2518 setSerialNumber(file, serialNumber);
2519 } catch (IOException e) {
2520 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2521 }
2522
2523 } else if (foundSerial != serialNumber) {
2524 throw new IOException("Found serial number " + foundSerial
2525 + " doesn't match expected " + serialNumber);
2526 }
2527 }
2528
2529 /**
2530 * Set serial number stored in user directory inode.
2531 *
2532 * @throws IOException if serial number was already set
2533 */
2534 private static void setSerialNumber(File file, int serialNumber)
2535 throws IOException {
2536 try {
2537 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2538 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2539 } catch (ErrnoException e) {
2540 throw e.rethrowAsIOException();
2541 }
2542 }
2543
2544 /**
2545 * Return serial number stored in user directory inode.
2546 *
2547 * @return parsed serial number, or -1 if not set
2548 */
2549 private static int getSerialNumber(File file) throws IOException {
2550 try {
2551 final byte[] buf = new byte[256];
2552 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2553 final String serial = new String(buf, 0, len);
2554 try {
2555 return Integer.parseInt(serial);
2556 } catch (NumberFormatException e) {
2557 throw new IOException("Bad serial number: " + serial);
2558 }
2559 } catch (ErrnoException e) {
2560 if (e.errno == OsConstants.ENODATA) {
2561 return -1;
2562 } else {
2563 throw e.rethrowAsIOException();
2564 }
2565 }
2566 }
2567
Amith Yamasani920ace02012-09-20 22:15:37 -07002568 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002569 public void setSeedAccountData(int userId, String accountName, String accountType,
2570 PersistableBundle accountOptions, boolean persist) {
2571 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2572 synchronized (mPackagesLock) {
2573 final UserData userData;
2574 synchronized (mUsersLock) {
2575 userData = getUserDataLU(userId);
2576 if (userData == null) {
2577 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2578 return;
2579 }
2580 userData.seedAccountName = accountName;
2581 userData.seedAccountType = accountType;
2582 userData.seedAccountOptions = accountOptions;
2583 userData.persistSeedData = persist;
2584 }
2585 if (persist) {
2586 writeUserLP(userData);
2587 }
2588 }
2589 }
2590
2591 @Override
2592 public String getSeedAccountName() throws RemoteException {
2593 checkManageUsersPermission("Cannot get seed account information");
2594 synchronized (mUsersLock) {
2595 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2596 return userData.seedAccountName;
2597 }
2598 }
2599
2600 @Override
2601 public String getSeedAccountType() throws RemoteException {
2602 checkManageUsersPermission("Cannot get seed account information");
2603 synchronized (mUsersLock) {
2604 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2605 return userData.seedAccountType;
2606 }
2607 }
2608
2609 @Override
2610 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2611 checkManageUsersPermission("Cannot get seed account information");
2612 synchronized (mUsersLock) {
2613 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2614 return userData.seedAccountOptions;
2615 }
2616 }
2617
2618 @Override
2619 public void clearSeedAccountData() throws RemoteException {
2620 checkManageUsersPermission("Cannot clear seed account information");
2621 synchronized (mPackagesLock) {
2622 UserData userData;
2623 synchronized (mUsersLock) {
2624 userData = getUserDataLU(UserHandle.getCallingUserId());
2625 if (userData == null) return;
2626 userData.clearSeedAccountData();
2627 }
2628 writeUserLP(userData);
2629 }
2630 }
2631
2632 @Override
2633 public boolean someUserHasSeedAccount(String accountName, String accountType)
2634 throws RemoteException {
2635 checkManageUsersPermission("Cannot check seed account information");
2636 synchronized (mUsersLock) {
2637 final int userSize = mUsers.size();
2638 for (int i = 0; i < userSize; i++) {
2639 final UserData data = mUsers.valueAt(i);
2640 if (data.info.isInitialized()) continue;
2641 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2642 continue;
2643 }
2644 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2645 continue;
2646 }
2647 return true;
2648 }
2649 }
2650 return false;
2651 }
2652
2653 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002654 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2655 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2656 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2657 }
2658
2659 int onShellCommand(Shell shell, String cmd) {
2660 if (cmd == null) {
2661 return shell.handleDefaultCommands(cmd);
2662 }
2663
2664 final PrintWriter pw = shell.getOutPrintWriter();
2665 try {
2666 switch(cmd) {
2667 case "list":
2668 return runList(pw);
2669 }
2670 } catch (RemoteException e) {
2671 pw.println("Remote exception: " + e);
2672 }
2673 return -1;
2674 }
2675
2676 private int runList(PrintWriter pw) throws RemoteException {
2677 final IActivityManager am = ActivityManagerNative.getDefault();
2678 final List<UserInfo> users = getUsers(false);
2679 if (users == null) {
2680 pw.println("Error: couldn't get users");
2681 return 1;
2682 } else {
2683 pw.println("Users:");
2684 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002685 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002686 pw.println("\t" + users.get(i).toString() + running);
2687 }
2688 return 0;
2689 }
2690 }
2691
2692 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002693 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2694 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2695 != PackageManager.PERMISSION_GRANTED) {
2696 pw.println("Permission Denial: can't dump UserManager from from pid="
2697 + Binder.getCallingPid()
2698 + ", uid=" + Binder.getCallingUid()
2699 + " without permission "
2700 + android.Manifest.permission.DUMP);
2701 return;
2702 }
2703
2704 long now = System.currentTimeMillis();
2705 StringBuilder sb = new StringBuilder();
2706 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002707 synchronized (mUsersLock) {
2708 pw.println("Users:");
2709 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002710 UserData userData = mUsers.valueAt(i);
2711 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002712 continue;
2713 }
Amith Yamasani12747872015-12-07 14:19:49 -08002714 UserInfo userInfo = userData.info;
2715 final int userId = userInfo.id;
2716 pw.print(" "); pw.print(userInfo);
2717 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002718 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002719 pw.print(" <removing> ");
2720 }
Amith Yamasani12747872015-12-07 14:19:49 -08002721 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002722 pw.print(" <partial>");
2723 }
2724 pw.println();
2725 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002726 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002727 pw.println("<unknown>");
2728 } else {
2729 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002730 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002731 sb.append(" ago");
2732 pw.println(sb);
2733 }
2734 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002735 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002736 pw.println("<unknown>");
2737 } else {
2738 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002739 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002740 sb.append(" ago");
2741 pw.println(sb);
2742 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002743 pw.print(" Has profile owner: ");
2744 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002745 pw.println(" Restrictions:");
2746 synchronized (mRestrictionsLock) {
2747 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002748 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002749 pw.println(" Device policy local restrictions:");
2750 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002751 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002752 pw.println(" Effective restrictions:");
2753 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002754 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002755 }
Amith Yamasani12747872015-12-07 14:19:49 -08002756
2757 if (userData.account != null) {
2758 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002759 pw.println();
2760 }
Amith Yamasani12747872015-12-07 14:19:49 -08002761
2762 if (userData.seedAccountName != null) {
2763 pw.print(" Seed account name: " + userData.seedAccountName);
2764 pw.println();
2765 if (userData.seedAccountType != null) {
2766 pw.print(" account type: " + userData.seedAccountType);
2767 pw.println();
2768 }
2769 if (userData.seedAccountOptions != null) {
2770 pw.print(" account options exist");
2771 pw.println();
2772 }
2773 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002774 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002775 }
Amith Yamasani12747872015-12-07 14:19:49 -08002776 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002777 pw.println(" Device policy global restrictions:");
2778 synchronized (mRestrictionsLock) {
2779 UserRestrictionsUtils
2780 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2781 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002782 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002783 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002784 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002785 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002786 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002787 synchronized (mUsersLock) {
2788 pw.println();
2789 pw.println(" Device managed: " + mIsDeviceManaged);
2790 }
Amith Yamasani12747872015-12-07 14:19:49 -08002791 // Dump some capabilities
2792 pw.println();
2793 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2794 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Amith Yamasani920ace02012-09-20 22:15:37 -07002795 }
2796 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002797
2798 final class MainHandler extends Handler {
2799
2800 @Override
2801 public void handleMessage(Message msg) {
2802 switch (msg.what) {
2803 case WRITE_USER_MSG:
2804 removeMessages(WRITE_USER_MSG, msg.obj);
2805 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002806 int userId = ((UserData) msg.obj).info.id;
2807 UserData userData = getUserDataNoChecks(userId);
2808 if (userData != null) {
2809 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002810 }
2811 }
2812 }
2813 }
2814 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002815
2816 /**
2817 * @param userId
2818 * @return whether the user has been initialized yet
2819 */
2820 boolean isInitialized(int userId) {
2821 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2822 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002823
2824 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002825 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002826 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2827 @Nullable Bundle globalRestrictions) {
2828 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2829 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002830 }
2831
2832 @Override
2833 public Bundle getBaseUserRestrictions(int userId) {
2834 synchronized (mRestrictionsLock) {
2835 return mBaseUserRestrictions.get(userId);
2836 }
2837 }
2838
2839 @Override
2840 public void setBaseUserRestrictionsByDpmsForMigration(
2841 int userId, Bundle baseRestrictions) {
2842 synchronized (mRestrictionsLock) {
2843 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002844 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002845 }
2846
Amith Yamasani12747872015-12-07 14:19:49 -08002847 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002848 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002849 if (userData != null) {
2850 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002851 } else {
2852 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2853 }
2854 }
2855 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002856
2857 @Override
2858 public boolean getUserRestriction(int userId, String key) {
2859 return getUserRestrictions(userId).getBoolean(key);
2860 }
2861
2862 @Override
2863 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2864 synchronized (mUserRestrictionsListeners) {
2865 mUserRestrictionsListeners.add(listener);
2866 }
2867 }
2868
2869 @Override
2870 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2871 synchronized (mUserRestrictionsListeners) {
2872 mUserRestrictionsListeners.remove(listener);
2873 }
2874 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002875
2876 @Override
2877 public void setDeviceManaged(boolean isManaged) {
2878 synchronized (mUsersLock) {
2879 mIsDeviceManaged = isManaged;
2880 }
2881 }
2882
2883 @Override
2884 public void setUserManaged(int userId, boolean isManaged) {
2885 synchronized (mUsersLock) {
2886 mIsUserManaged.put(userId, isManaged);
2887 }
2888 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01002889
2890 @Override
2891 public void setUserIcon(int userId, Bitmap bitmap) {
2892 long ident = Binder.clearCallingIdentity();
2893 try {
2894 synchronized (mPackagesLock) {
2895 UserData userData = getUserDataNoChecks(userId);
2896 if (userData == null || userData.info.partial) {
2897 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
2898 return;
2899 }
2900 writeBitmapLP(userData.info, bitmap);
2901 writeUserLP(userData);
2902 }
2903 sendUserInfoChangedBroadcast(userId);
2904 } finally {
2905 Binder.restoreCallingIdentity(ident);
2906 }
2907 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002908 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002909
2910 private class Shell extends ShellCommand {
2911 @Override
2912 public int onCommand(String cmd) {
2913 return onShellCommand(this, cmd);
2914 }
2915
2916 @Override
2917 public void onHelp() {
2918 final PrintWriter pw = getOutPrintWriter();
2919 pw.println("User manager (user) commands:");
2920 pw.println(" help");
2921 pw.println(" Print this help text.");
2922 pw.println("");
2923 pw.println(" list");
2924 pw.println(" Prints all users on the system.");
2925 }
2926 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002927
2928 private static void debug(String message) {
2929 Log.d(LOG_TAG, message +
2930 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2931 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002932}