blob: 13d7c35df5d4c75089d31e48bd616128c6324b48 [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");
Jason Monk9a944532014-07-08 09:31:21 -0400732 long ident = Binder.clearCallingIdentity();
733 try {
734 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800735 UserData userData = getUserDataNoChecks(userId);
736 if (userData == null || userData.info.partial) {
Jason Monk9a944532014-07-08 09:31:21 -0400737 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
738 return;
739 }
Amith Yamasani12747872015-12-07 14:19:49 -0800740 writeBitmapLP(userData.info, bitmap);
741 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700742 }
Jason Monk9a944532014-07-08 09:31:21 -0400743 sendUserInfoChangedBroadcast(userId);
744 } finally {
745 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700746 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700747 }
748
749 private void sendUserInfoChangedBroadcast(int userId) {
750 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
751 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
752 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700753 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700754 }
755
Amith Yamasani258848d2012-08-10 17:06:33 -0700756 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100757 public ParcelFileDescriptor getUserIcon(int userId) {
758 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700759 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700760 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700761 if (info == null || info.partial) {
762 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
763 return null;
764 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700765 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100766 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
767 || callingGroupId != info.profileGroupId) {
768 checkManageUsersPermission("get the icon of a user who is not related");
769 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700770 if (info.iconPath == null) {
771 return null;
772 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100773 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700774 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100775
776 try {
777 return ParcelFileDescriptor.open(
778 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
779 } catch (FileNotFoundException e) {
780 Log.e(LOG_TAG, "Couldn't find icon file", e);
781 }
782 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700783 }
784
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700785 public void makeInitialized(int userId) {
786 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800787 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800788 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800789 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800790 userData = mUsers.get(userId);
791 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700792 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800793 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700794 }
Amith Yamasani12747872015-12-07 14:19:49 -0800795 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
796 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800797 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700798 }
799 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800800 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800801 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800802 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700803 }
804
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700805 /**
806 * If default guest restrictions haven't been initialized yet, add the basic
807 * restrictions.
808 */
809 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800810 synchronized (mGuestRestrictions) {
811 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800812 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800813 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
814 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
815 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700816 }
817 }
818
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800819 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530820 public Bundle getDefaultGuestRestrictions() {
821 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800822 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530823 return new Bundle(mGuestRestrictions);
824 }
825 }
826
827 @Override
828 public void setDefaultGuestRestrictions(Bundle restrictions) {
829 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800830 synchronized (mGuestRestrictions) {
831 mGuestRestrictions.clear();
832 mGuestRestrictions.putAll(restrictions);
833 }
834 synchronized (mPackagesLock) {
835 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530836 }
837 }
838
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800839 /**
840 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
841 */
842 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
843 @Nullable Bundle global) {
844 Preconditions.checkNotNull(local);
845 boolean globalChanged = false;
846 boolean localChanged;
847 synchronized (mRestrictionsLock) {
848 if (global != null) {
849 // Update global.
850 globalChanged = !UserRestrictionsUtils.areEqual(
851 mDevicePolicyGlobalUserRestrictions, global);
852 if (globalChanged) {
853 mDevicePolicyGlobalUserRestrictions = global;
854 }
855 }
856 {
857 // Update local.
858 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
859 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
860 if (localChanged) {
861 mDevicePolicyLocalUserRestrictions.put(userId, local);
862 }
863 }
864 }
865 if (DBG) {
866 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
867 + " global=" + global + (globalChanged ? " (changed)" : "")
868 + " local=" + local + (localChanged ? " (changed)" : "")
869 );
870 }
871 // Don't call them within the mRestrictionsLock.
872 synchronized (mPackagesLock) {
873 if (globalChanged) {
874 writeUserListLP();
875 }
876 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800877 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800878 }
879 }
880
881 synchronized (mRestrictionsLock) {
882 if (globalChanged) {
883 applyUserRestrictionsForAllUsersLR();
884 } else if (localChanged) {
885 applyUserRestrictionsLR(userId);
886 }
887 }
888 }
889
Makoto Onuki068c54a2015-10-13 14:34:03 -0700890 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700891 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800892 final Bundle baseRestrictions =
893 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
894 final Bundle global = mDevicePolicyGlobalUserRestrictions;
895 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700896
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800897 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
898 // Common case first.
899 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700900 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800901 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
902 UserRestrictionsUtils.merge(effective, global);
903 UserRestrictionsUtils.merge(effective, local);
904
Makoto Onuki068c54a2015-10-13 14:34:03 -0700905 return effective;
906 }
907
908 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700909 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700910 if (DBG) {
911 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
912 }
913 mCachedEffectiveUserRestrictions.remove(userId);
914 }
915
916 private Bundle getEffectiveUserRestrictions(int userId) {
917 synchronized (mRestrictionsLock) {
918 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
919 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700920 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700921 mCachedEffectiveUserRestrictions.put(userId, restrictions);
922 }
923 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700924 }
925 }
926
Makoto Onuki068c54a2015-10-13 14:34:03 -0700927 /** @return a specific user restriction that's in effect currently. */
928 @Override
929 public boolean hasUserRestriction(String restrictionKey, int userId) {
930 Bundle restrictions = getEffectiveUserRestrictions(userId);
931 return restrictions != null && restrictions.getBoolean(restrictionKey);
932 }
933
934 /**
935 * @return UserRestrictions that are in effect currently. This always returns a new
936 * {@link Bundle}.
937 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700938 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800939 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800940 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800941 }
942
943 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000944 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
945 checkManageUsersPermission("hasBaseUserRestriction");
946 synchronized (mRestrictionsLock) {
947 Bundle bundle = mBaseUserRestrictions.get(userId);
948 return (bundle != null && bundle.getBoolean(restrictionKey, false));
949 }
950 }
951
952 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700953 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700954 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700955 synchronized (mRestrictionsLock) {
956 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
957 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800958 final Bundle newRestrictions = UserRestrictionsUtils.clone(
959 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700960 newRestrictions.putBoolean(key, value);
961
Fyodor Kupolov82402752015-10-28 14:54:51 -0700962 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700963 }
964 }
965
Makoto Onuki068c54a2015-10-13 14:34:03 -0700966 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800967 * Optionally updating user restrictions, calculate the effective user restrictions and also
968 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700969 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800970 * @param newRestrictions User restrictions to set.
971 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700972 * @param userId target user ID.
973 */
974 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700975 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700976 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800977
978 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
979 mAppliedUserRestrictions.get(userId));
980
981 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700982 if (newRestrictions != null) {
983 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800984 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
985
986 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700987 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
988 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800989
990 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
991 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -0800992 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800993 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700994 }
995
Fyodor Kupolov82402752015-10-28 14:54:51 -0700996 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700997
Makoto Onuki759a7632015-10-28 16:43:10 -0700998 mCachedEffectiveUserRestrictions.put(userId, effective);
999
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001000 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001001 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001002 debug("Applying user restrictions: userId=" + userId
1003 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001004 }
1005
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001006 if (mAppOpsService != null) { // We skip it until system-ready.
1007 final long token = Binder.clearCallingIdentity();
1008 try {
1009 mAppOpsService.setUserRestrictions(effective, userId);
1010 } catch (RemoteException e) {
1011 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1012 } finally {
1013 Binder.restoreCallingIdentity(token);
1014 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001015 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001016
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001017 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001018
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001019 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001020 }
1021
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001022 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001023 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001024 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1025 // actually, but we still need some kind of synchronization otherwise we might end up
1026 // calling listeners out-of-order, thus "LR".
1027
1028 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1029 return;
1030 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001031
1032 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1033 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1034
1035 mHandler.post(new Runnable() {
1036 @Override
1037 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001038 UserRestrictionsUtils.applyUserRestrictions(
1039 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001040
Makoto Onukid45a4a22015-11-02 17:17:38 -08001041 final UserRestrictionsListener[] listeners;
1042 synchronized (mUserRestrictionsListeners) {
1043 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1044 mUserRestrictionsListeners.toArray(listeners);
1045 }
1046 for (int i = 0; i < listeners.length; i++) {
1047 listeners[i].onUserRestrictionsChanged(userId,
1048 newRestrictionsFinal, prevRestrictionsFinal);
1049 }
1050 }
1051 });
1052 }
1053
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001054 // Package private for the inner class.
1055 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001056 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001057 }
1058
1059 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001060 // Package private for the inner class.
1061 void applyUserRestrictionsForAllUsersLR() {
1062 if (DBG) {
1063 debug("applyUserRestrictionsForAllUsersLR");
1064 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001065 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001066 mCachedEffectiveUserRestrictions.clear();
1067
Makoto Onuki068c54a2015-10-13 14:34:03 -07001068 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1069 // it on a handler.
1070 final Runnable r = new Runnable() {
1071 @Override
1072 public void run() {
1073 // Then get the list of running users.
1074 final int[] runningUsers;
1075 try {
1076 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1077 } catch (RemoteException e) {
1078 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1079 return;
1080 }
1081 // Then re-calculate the effective restrictions and apply, only for running users.
1082 // It's okay if a new user has started after the getRunningUserIds() call,
1083 // because we'll do the same thing (re-calculate the restrictions and apply)
1084 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001085 synchronized (mRestrictionsLock) {
1086 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001087 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001088 }
1089 }
1090 }
1091 };
1092 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001093 }
1094
Amith Yamasani258848d2012-08-10 17:06:33 -07001095 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001096 * Check if we've hit the limit of how many users can be created.
1097 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001098 private boolean isUserLimitReached() {
1099 int count;
1100 synchronized (mUsersLock) {
1101 count = getAliveUsersExcludingGuestsCountLU();
1102 }
1103 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001104 }
1105
1106 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001107 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001108 checkManageUsersPermission("check if more managed profiles can be added.");
1109 if (ActivityManager.isLowRamDeviceStatic()) {
1110 return false;
1111 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001112 if (!mContext.getPackageManager().hasSystemFeature(
1113 PackageManager.FEATURE_MANAGED_USERS)) {
1114 return false;
1115 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001116 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001117 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1118 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1119 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001120 return false;
1121 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001122 synchronized(mUsersLock) {
1123 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001124 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001125 return false;
1126 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001127 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1128 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001129 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001130 return usersCountAfterRemoving == 1
1131 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001132 }
1133 }
1134
Fyodor Kupolov82402752015-10-28 14:54:51 -07001135 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001136 int aliveUserCount = 0;
1137 final int totalUserCount = mUsers.size();
1138 // Skip over users being removed
1139 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001140 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001141 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001142 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001143 aliveUserCount++;
1144 }
1145 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001146 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001147 }
1148
1149 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001150 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001151 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1152 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1153 * permissions can make certain calls to the UserManager.
1154 *
1155 * @param message used as message if SecurityException is thrown
1156 * @throws SecurityException if the caller does not have enough privilege.
1157 */
1158 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1159 final int uid = Binder.getCallingUid();
1160 if (uid != Process.SYSTEM_UID && uid != 0
1161 && ActivityManager.checkComponentPermission(
1162 Manifest.permission.MANAGE_USERS,
1163 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1164 && ActivityManager.checkComponentPermission(
1165 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1166 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1167 throw new SecurityException(
1168 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1169 + message);
1170 }
1171 }
1172
1173 /**
1174 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001175 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001176 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001177 *
1178 * @param message used as message if SecurityException is thrown
1179 * @throws SecurityException if the caller is not system or root
1180 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001181 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001182 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001183 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001184 && ActivityManager.checkComponentPermission(
1185 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001186 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1187 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1188 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001189 }
1190
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001191 /**
1192 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1193 * UserManager.
1194 *
1195 * @param message used as message if SecurityException is thrown
1196 * @throws SecurityException if the caller is not system or root
1197 */
1198 private static void checkSystemOrRoot(String message) {
1199 final int uid = Binder.getCallingUid();
1200 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1201 throw new SecurityException("Only system may: " + message);
1202 }
1203 }
1204
Fyodor Kupolov82402752015-10-28 14:54:51 -07001205 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001206 try {
1207 File dir = new File(mUsersDir, Integer.toString(info.id));
1208 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001209 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001210 if (!dir.exists()) {
1211 dir.mkdir();
1212 FileUtils.setPermissions(
1213 dir.getPath(),
1214 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1215 -1, -1);
1216 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001217 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001218 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1219 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001220 info.iconPath = file.getAbsolutePath();
1221 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001222 try {
1223 os.close();
1224 } catch (IOException ioe) {
1225 // What the ... !
1226 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001227 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001228 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001229 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001230 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001231 }
1232
Amith Yamasani0b285492011-04-14 17:35:23 -07001233 /**
1234 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1235 * cache it elsewhere.
1236 * @return the array of user ids.
1237 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001238 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001239 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001240 return mUserIds;
1241 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001242 }
1243
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001244 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001245 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001246 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001247 return;
1248 }
1249 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001250 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001251 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001252 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001253 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001254 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001255 int type;
1256 while ((type = parser.next()) != XmlPullParser.START_TAG
1257 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001258 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001259 }
1260
1261 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001262 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001263 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001264 return;
1265 }
1266
Amith Yamasani2a003292012-08-14 18:25:45 -07001267 mNextSerialNumber = -1;
1268 if (parser.getName().equals(TAG_USERS)) {
1269 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1270 if (lastSerialNumber != null) {
1271 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1272 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001273 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1274 if (versionNumber != null) {
1275 mUserVersion = Integer.parseInt(versionNumber);
1276 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001277 }
1278
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001279 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1280
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001281 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301282 if (type == XmlPullParser.START_TAG) {
1283 final String name = parser.getName();
1284 if (name.equals(TAG_USER)) {
1285 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001286
Amith Yamasani12747872015-12-07 14:19:49 -08001287 UserData userData = readUserLP(Integer.parseInt(id));
1288
1289 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001290 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001291 mUsers.put(userData.info.id, userData);
1292 if (mNextSerialNumber < 0
1293 || mNextSerialNumber <= userData.info.id) {
1294 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001295 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301296 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001297 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301298 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001299 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1300 && type != XmlPullParser.END_TAG) {
1301 if (type == XmlPullParser.START_TAG) {
1302 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001303 synchronized (mGuestRestrictions) {
1304 UserRestrictionsUtils
1305 .readRestrictions(parser, mGuestRestrictions);
1306 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001307 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1308 ) {
1309 UserRestrictionsUtils.readRestrictions(parser,
1310 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001311 }
1312 break;
1313 }
1314 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001315 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001316 }
1317 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001318 synchronized (mRestrictionsLock) {
1319 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1320 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001321 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001322 upgradeIfNecessaryLP();
1323 } catch (IOException | XmlPullParserException e) {
1324 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001325 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001326 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001327 }
1328 }
1329
Amith Yamasani6f34b412012-10-22 18:19:27 -07001330 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001331 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001332 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001333 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001334 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001335 int userVersion = mUserVersion;
1336 if (userVersion < 1) {
1337 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001338 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1339 if ("Primary".equals(userData.info.name)) {
1340 userData.info.name =
1341 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1342 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001343 }
1344 userVersion = 1;
1345 }
1346
Amith Yamasanibc9625052012-11-15 14:39:18 -08001347 if (userVersion < 2) {
1348 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001349 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1350 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1351 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1352 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001353 }
1354 userVersion = 2;
1355 }
1356
Amith Yamasani350962c2013-08-06 11:18:53 -07001357
Amith Yamasani5e486f52013-08-07 11:06:44 -07001358 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001359 userVersion = 4;
1360 }
1361
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001362 if (userVersion < 5) {
1363 initDefaultGuestRestrictions();
1364 userVersion = 5;
1365 }
1366
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001367 if (userVersion < 6) {
1368 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001369 synchronized (mUsersLock) {
1370 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001371 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001372 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001373 if (!splitSystemUser && userData.info.isRestricted()
1374 && (userData.info.restrictedProfileParentId
1375 == UserInfo.NO_PROFILE_GROUP_ID)) {
1376 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1377 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001378 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001379 }
1380 }
1381 userVersion = 6;
1382 }
1383
Amith Yamasani6f34b412012-10-22 18:19:27 -07001384 if (userVersion < USER_VERSION) {
1385 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1386 + USER_VERSION);
1387 } else {
1388 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001389
1390 if (originalVersion < mUserVersion) {
1391 writeUserListLP();
1392 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001393 }
1394 }
1395
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001396 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001397 int flags = UserInfo.FLAG_INITIALIZED;
1398 // In split system user mode, the admin and primary flags are assigned to the first human
1399 // user.
1400 if (!UserManager.isSplitSystemUser()) {
1401 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1402 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001403 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001404 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001405 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001406 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001407 UserData userData = new UserData();
1408 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001409 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001410 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001411 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001412 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001413 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001414
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001415 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001416 synchronized (mRestrictionsLock) {
1417 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1418 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001419
Fyodor Kupolov82402752015-10-28 14:54:51 -07001420 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001421 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001422
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001423 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001424 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001425 }
1426
Amith Yamasani12747872015-12-07 14:19:49 -08001427 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001428 if (DBG) {
1429 debug("scheduleWriteUser");
1430 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001431 // No need to wrap it within a lock -- worst case, we'll just post the same message
1432 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001433 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1434 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001435 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1436 }
1437 }
1438
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001439 /*
1440 * Writes the user file in this format:
1441 *
1442 * <user flags="20039023" id="0">
1443 * <name>Primary</name>
1444 * </user>
1445 */
Amith Yamasani12747872015-12-07 14:19:49 -08001446 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001447 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001448 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001450 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001451 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001452 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001453 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001454 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1455
1456 // XmlSerializer serializer = XmlUtils.serializerInstance();
1457 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001458 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001459 serializer.startDocument(null, true);
1460 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1461
Amith Yamasani12747872015-12-07 14:19:49 -08001462 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001463 serializer.startTag(null, TAG_USER);
1464 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001465 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001466 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001467 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1468 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1469 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001470 if (userInfo.iconPath != null) {
1471 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1472 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001473 if (userInfo.partial) {
1474 serializer.attribute(null, ATTR_PARTIAL, "true");
1475 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001476 if (userInfo.guestToRemove) {
1477 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1478 }
Kenny Guy2a764942014-04-02 13:29:20 +01001479 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1480 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1481 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001482 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001483 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1484 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1485 Integer.toString(userInfo.restrictedProfileParentId));
1486 }
Amith Yamasani12747872015-12-07 14:19:49 -08001487 // Write seed data
1488 if (userData.persistSeedData) {
1489 if (userData.seedAccountName != null) {
1490 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1491 }
1492 if (userData.seedAccountType != null) {
1493 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1494 }
1495 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001496 serializer.startTag(null, TAG_NAME);
1497 serializer.text(userInfo.name);
1498 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001499 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001500 UserRestrictionsUtils.writeRestrictions(serializer,
1501 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1502 UserRestrictionsUtils.writeRestrictions(serializer,
1503 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1504 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001505 }
Amith Yamasani12747872015-12-07 14:19:49 -08001506
1507 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001508 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001509 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001510 serializer.endTag(null, TAG_ACCOUNT);
1511 }
1512
Amith Yamasani12747872015-12-07 14:19:49 -08001513 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1514 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1515 userData.seedAccountOptions.saveToXml(serializer);
1516 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1517 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001518 serializer.endTag(null, TAG_USER);
1519
1520 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001521 userFile.finishWrite(fos);
1522 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001523 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001524 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001525 }
1526 }
1527
1528 /*
1529 * Writes the user list file in this format:
1530 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001531 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001532 * <user id="0"></user>
1533 * <user id="2"></user>
1534 * </users>
1535 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001536 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001537 if (DBG) {
1538 debug("writeUserList");
1539 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001540 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001541 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001542 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001543 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001544 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1545
1546 // XmlSerializer serializer = XmlUtils.serializerInstance();
1547 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001548 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001549 serializer.startDocument(null, true);
1550 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1551
1552 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001553 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001554 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001555
Adam Lesinskieddeb492014-09-08 17:50:03 -07001556 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001557 synchronized (mGuestRestrictions) {
1558 UserRestrictionsUtils
1559 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1560 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301561 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001562 synchronized (mRestrictionsLock) {
1563 UserRestrictionsUtils.writeRestrictions(serializer,
1564 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1565 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001566 int[] userIdsToWrite;
1567 synchronized (mUsersLock) {
1568 userIdsToWrite = new int[mUsers.size()];
1569 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001570 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001571 userIdsToWrite[i] = user.id;
1572 }
1573 }
1574 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001575 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001576 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001577 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001578 }
1579
1580 serializer.endTag(null, TAG_USERS);
1581
1582 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001583 userListFile.finishWrite(fos);
1584 } catch (Exception e) {
1585 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001586 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001587 }
1588 }
1589
Amith Yamasani12747872015-12-07 14:19:49 -08001590 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001591 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001592 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001593 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001594 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001595 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001596 long creationTime = 0L;
1597 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001598 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001599 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001600 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001601 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001602 boolean persistSeedData = false;
1603 String seedAccountName = null;
1604 String seedAccountType = null;
1605 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001606 Bundle baseRestrictions = new Bundle();
1607 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001608
1609 FileInputStream fis = null;
1610 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001611 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001612 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001613 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001614 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001615 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001616 int type;
1617 while ((type = parser.next()) != XmlPullParser.START_TAG
1618 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001619 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001620 }
1621
1622 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001623 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001624 return null;
1625 }
1626
1627 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001628 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1629 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001630 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001631 return null;
1632 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001633 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1634 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001635 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001636 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1637 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001638 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1639 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001640 restrictedProfileParentId = readIntAttribute(parser,
1641 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001642 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1643 if ("true".equals(valueString)) {
1644 partial = true;
1645 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001646 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1647 if ("true".equals(valueString)) {
1648 guestToRemove = true;
1649 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001650
Amith Yamasani12747872015-12-07 14:19:49 -08001651 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1652 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1653 if (seedAccountName != null || seedAccountType != null) {
1654 persistSeedData = true;
1655 }
1656
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001657 int outerDepth = parser.getDepth();
1658 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1659 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1660 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1661 continue;
1662 }
1663 String tag = parser.getName();
1664 if (TAG_NAME.equals(tag)) {
1665 type = parser.next();
1666 if (type == XmlPullParser.TEXT) {
1667 name = parser.getText();
1668 }
1669 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001670 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1671 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1672 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001673 } else if (TAG_ACCOUNT.equals(tag)) {
1674 type = parser.next();
1675 if (type == XmlPullParser.TEXT) {
1676 account = parser.getText();
1677 }
Amith Yamasani12747872015-12-07 14:19:49 -08001678 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1679 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1680 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001681 }
1682 }
1683 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001684
Amith Yamasani12747872015-12-07 14:19:49 -08001685 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001686 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001687 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001688 userInfo.creationTime = creationTime;
1689 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001690 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001691 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001692 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001693 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001694
1695 // Create the UserData object that's internal to this class
1696 UserData userData = new UserData();
1697 userData.info = userInfo;
1698 userData.account = account;
1699 userData.seedAccountName = seedAccountName;
1700 userData.seedAccountType = seedAccountType;
1701 userData.persistSeedData = persistSeedData;
1702 userData.seedAccountOptions = seedAccountOptions;
1703
Makoto Onuki068c54a2015-10-13 14:34:03 -07001704 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001705 mBaseUserRestrictions.put(id, baseRestrictions);
1706 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001707 }
Amith Yamasani12747872015-12-07 14:19:49 -08001708 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001709 } catch (IOException ioe) {
1710 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001711 } finally {
1712 if (fis != null) {
1713 try {
1714 fis.close();
1715 } catch (IOException e) {
1716 }
1717 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001718 }
1719 return null;
1720 }
1721
Amith Yamasani920ace02012-09-20 22:15:37 -07001722 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1723 String valueString = parser.getAttributeValue(null, attr);
1724 if (valueString == null) return defaultValue;
1725 try {
1726 return Integer.parseInt(valueString);
1727 } catch (NumberFormatException nfe) {
1728 return defaultValue;
1729 }
1730 }
1731
1732 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1733 String valueString = parser.getAttributeValue(null, attr);
1734 if (valueString == null) return defaultValue;
1735 try {
1736 return Long.parseLong(valueString);
1737 } catch (NumberFormatException nfe) {
1738 return defaultValue;
1739 }
1740 }
1741
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001742 private boolean isPackageInstalled(String pkg, int userId) {
1743 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1744 PackageManager.GET_UNINSTALLED_PACKAGES,
1745 userId);
1746 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1747 return false;
1748 }
1749 return true;
1750 }
1751
Amith Yamasanib82add22013-07-09 11:24:44 -07001752 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001753 * Removes the app restrictions file for a specific package and user id, if it exists.
1754 */
1755 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1756 synchronized (mPackagesLock) {
1757 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001758 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001759 if (resFile.exists()) {
1760 resFile.delete();
1761 }
1762 }
1763 }
1764
Kenny Guya52dc3e2014-02-11 15:33:14 +00001765 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001766 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001767 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001768 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001769 }
1770
Amith Yamasani258848d2012-08-10 17:06:33 -07001771 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001772 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001773 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001774 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001775 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001776
Jessica Hummelbe81c802014-04-22 15:49:22 +01001777 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001778 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001779 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1780 return null;
1781 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001782 if (ActivityManager.isLowRamDeviceStatic()) {
1783 return null;
1784 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001785 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001786 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001787 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001788 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001789 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001790 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001791 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001792 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001793 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001794 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001795 if (parentId != UserHandle.USER_NULL) {
1796 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001797 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001798 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001799 if (parent == null) return null;
1800 }
1801 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1802 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1803 return null;
1804 }
1805 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1806 // If we're not adding a guest user or a managed profile and the limit has
1807 // been reached, cannot add a user.
1808 return null;
1809 }
1810 // If we're adding a guest and there already exists one, bail.
1811 if (isGuest && findCurrentGuestUser() != null) {
1812 return null;
1813 }
1814 // In legacy mode, restricted profile's parent can only be the owner user
1815 if (isRestricted && !UserManager.isSplitSystemUser()
1816 && (parentId != UserHandle.USER_SYSTEM)) {
1817 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1818 return null;
1819 }
1820 if (isRestricted && UserManager.isSplitSystemUser()) {
1821 if (parent == null) {
1822 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1823 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001824 return null;
1825 }
Amith Yamasani12747872015-12-07 14:19:49 -08001826 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001827 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1828 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001829 return null;
1830 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001831 }
1832 // In split system user mode, we assign the first human user the primary flag.
1833 // And if there is no device owner, we also assign the admin flag to primary user.
1834 if (UserManager.isSplitSystemUser()
1835 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1836 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001837 synchronized (mUsersLock) {
1838 if (!mIsDeviceManaged) {
1839 flags |= UserInfo.FLAG_ADMIN;
1840 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001841 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001842 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001843
Amith Yamasani12747872015-12-07 14:19:49 -08001844 if (parent != null && parent.info.isEphemeral()) {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001845 flags |= UserInfo.FLAG_EPHEMERAL;
1846 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001847 userId = getNextAvailableId();
1848 userInfo = new UserInfo(userId, name, null, flags);
1849 userInfo.serialNumber = mNextSerialNumber++;
1850 long now = System.currentTimeMillis();
1851 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1852 userInfo.partial = true;
Amith Yamasani12747872015-12-07 14:19:49 -08001853 userData = new UserData();
1854 userData.info = userInfo;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001855 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1856 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001857 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001858 }
1859 writeUserListLP();
1860 if (parent != null) {
1861 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001862 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1863 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001864 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001865 }
Amith Yamasani12747872015-12-07 14:19:49 -08001866 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001867 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001868 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1869 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001870 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001871 }
Amith Yamasani12747872015-12-07 14:19:49 -08001872 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001873 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001874 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001875 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001876 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001877 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001878 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1879 final String volumeUuid = vol.getFsUuid();
1880 try {
1881 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001882 storage.prepareUserStorage(
1883 volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001884 enforceSerialNumber(userDir, userInfo.serialNumber);
1885 } catch (IOException e) {
1886 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1887 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001888 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001889 mPm.createNewUser(userId);
1890 userInfo.partial = false;
1891 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001892 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001893 }
1894 updateUserIds();
1895 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001896 if (isGuest) {
1897 synchronized (mGuestRestrictions) {
1898 restrictions.putAll(mGuestRestrictions);
1899 }
1900 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001901 synchronized (mRestrictionsLock) {
1902 mBaseUserRestrictions.append(userId, restrictions);
1903 }
1904 mPm.newUserCreated(userId);
1905 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1906 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1907 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1908 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001909 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001910 } finally {
1911 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001912 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001913 return userInfo;
1914 }
1915
Amith Yamasani0b285492011-04-14 17:35:23 -07001916 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001917 * @hide
1918 */
Amith Yamasani12747872015-12-07 14:19:49 -08001919 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001920 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1921 checkManageUsersPermission("setupRestrictedProfile");
1922 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1923 if (user == null) {
1924 return null;
1925 }
1926 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1927 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1928 // the putIntForUser() will fail.
1929 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1930 android.provider.Settings.Secure.LOCATION_MODE,
1931 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1932 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1933 return user;
1934 }
1935
1936 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001937 * Find the current guest user. If the Guest user is partial,
1938 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001939 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001940 private UserInfo findCurrentGuestUser() {
1941 synchronized (mUsersLock) {
1942 final int size = mUsers.size();
1943 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001944 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001945 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1946 return user;
1947 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001948 }
1949 }
1950 return null;
1951 }
1952
1953 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001954 * Mark this guest user for deletion to allow us to create another guest
1955 * and switch to that user before actually removing this guest.
1956 * @param userHandle the userid of the current guest
1957 * @return whether the user could be marked for deletion
1958 */
Amith Yamasani12747872015-12-07 14:19:49 -08001959 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07001960 public boolean markGuestForDeletion(int userHandle) {
1961 checkManageUsersPermission("Only the system can remove users");
1962 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1963 UserManager.DISALLOW_REMOVE_USER, false)) {
1964 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1965 return false;
1966 }
1967
1968 long ident = Binder.clearCallingIdentity();
1969 try {
Amith Yamasani12747872015-12-07 14:19:49 -08001970 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07001971 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001972 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001973 userData = mUsers.get(userHandle);
1974 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001975 return false;
1976 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001977 }
Amith Yamasani12747872015-12-07 14:19:49 -08001978 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07001979 return false;
1980 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001981 // We set this to a guest user that is to be removed. This is a temporary state
1982 // where we are allowed to add new Guest users, even if this one is still not
1983 // removed. This user will still show up in getUserInfo() calls.
1984 // If we don't get around to removing this Guest user, it will be purged on next
1985 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08001986 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001987 // Mark it as disabled, so that it isn't returned any more when
1988 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08001989 userData.info.flags |= UserInfo.FLAG_DISABLED;
1990 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07001991 }
1992 } finally {
1993 Binder.restoreCallingIdentity(ident);
1994 }
1995 return true;
1996 }
1997
1998 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001999 * Removes a user and all data directories created for that user. This method should be called
2000 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002001 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002002 */
Amith Yamasani12747872015-12-07 14:19:49 -08002003 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002004 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002005 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002006 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2007 UserManager.DISALLOW_REMOVE_USER, false)) {
2008 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2009 return false;
2010 }
2011
Kenny Guyee58b4f2014-05-23 15:19:53 +01002012 long ident = Binder.clearCallingIdentity();
2013 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002014 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002015 int currentUser = ActivityManager.getCurrentUser();
2016 if (currentUser == userHandle) {
2017 Log.w(LOG_TAG, "Current user cannot be removed");
2018 return false;
2019 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002020 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002021 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002022 userData = mUsers.get(userHandle);
2023 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002024 return false;
2025 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002026
Fyodor Kupolov82402752015-10-28 14:54:51 -07002027 // We remember deleted user IDs to prevent them from being
2028 // reused during the current boot; they can still be reused
2029 // after a reboot.
2030 mRemovingUserIds.put(userHandle, true);
2031 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002032
Kenny Guyee58b4f2014-05-23 15:19:53 +01002033 try {
2034 mAppOpsService.removeUser(userHandle);
2035 } catch (RemoteException e) {
2036 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2037 }
2038 // Set this to a partially created user, so that the user will be purged
2039 // on next startup, in case the runtime stops now before stopping and
2040 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002041 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002042 // Mark it as disabled, so that it isn't returned any more when
2043 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002044 userData.info.flags |= UserInfo.FLAG_DISABLED;
2045 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002046 }
2047
Amith Yamasani12747872015-12-07 14:19:49 -08002048 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2049 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002050 // Send broadcast to notify system that the user removed was a
2051 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002052 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002053 }
2054
2055 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2056 int res;
2057 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002058 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2059 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002060 @Override
2061 public void userStopped(int userId) {
2062 finishRemoveUser(userId);
2063 }
2064 @Override
2065 public void userStopAborted(int userId) {
2066 }
2067 });
2068 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002069 return false;
2070 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002071 return res == ActivityManager.USER_OP_SUCCESS;
2072 } finally {
2073 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002074 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002075 }
2076
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002077 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002078 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002079 // Let other services shutdown any activity and clean up their state before completely
2080 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002081 long ident = Binder.clearCallingIdentity();
2082 try {
2083 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2084 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002085 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2086 android.Manifest.permission.MANAGE_USERS,
2087
2088 new BroadcastReceiver() {
2089 @Override
2090 public void onReceive(Context context, Intent intent) {
2091 if (DBG) {
2092 Slog.i(LOG_TAG,
2093 "USER_REMOVED broadcast sent, cleaning up user data "
2094 + userHandle);
2095 }
2096 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002097 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002098 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002099 // Clean up any ActivityManager state
2100 LocalServices.getService(ActivityManagerInternal.class)
2101 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002102 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002103 }
2104 }.start();
2105 }
2106 },
2107
2108 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002109 } finally {
2110 Binder.restoreCallingIdentity(ident);
2111 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002112 }
2113
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002114 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002115 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002116 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002117 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002118
2119 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002120 synchronized (mUsersLock) {
2121 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002122 mIsUserManaged.delete(userHandle);
2123 }
2124 synchronized (mRestrictionsLock) {
2125 mBaseUserRestrictions.remove(userHandle);
2126 mAppliedUserRestrictions.remove(userHandle);
2127 mCachedEffectiveUserRestrictions.remove(userHandle);
2128 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002129 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002130 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002131 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002132 userFile.delete();
2133 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002134 synchronized (mPackagesLock) {
2135 writeUserListLP();
2136 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002137 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002138 File userDir = Environment.getUserSystemDirectory(userHandle);
2139 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2140 if (userDir.renameTo(renamedUserDir)) {
2141 removeDirectoryRecursive(renamedUserDir);
2142 } else {
2143 removeDirectoryRecursive(userDir);
2144 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002145 }
2146
Amith Yamasani61f57372012-08-31 12:12:28 -07002147 private void removeDirectoryRecursive(File parent) {
2148 if (parent.isDirectory()) {
2149 String[] files = parent.list();
2150 for (String filename : files) {
2151 File child = new File(parent, filename);
2152 removeDirectoryRecursive(child);
2153 }
2154 }
2155 parent.delete();
2156 }
2157
Kenny Guyf8d3a232014-05-15 16:09:52 +01002158 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002159 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002160 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2161 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002162 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002163 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002164 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002165 }
2166
Amith Yamasani2a003292012-08-14 18:25:45 -07002167 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002168 public Bundle getApplicationRestrictions(String packageName) {
2169 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2170 }
2171
2172 @Override
2173 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002174 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002175 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002176 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002177 }
2178 synchronized (mPackagesLock) {
2179 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002180 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002181 }
2182 }
2183
2184 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002185 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002186 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002187 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002188 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002189 if (restrictions == null || restrictions.isEmpty()) {
2190 cleanAppRestrictionsForPackage(packageName, userId);
2191 } else {
2192 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002193 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002194 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002195 }
Robin Lee66e5d962014-04-09 16:44:21 +01002196
Kenny Guyd21b2182014-07-17 16:38:55 +01002197 if (isPackageInstalled(packageName, userId)) {
2198 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2199 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2200 changeIntent.setPackage(packageName);
2201 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2202 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2203 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002204 }
2205
2206 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002207 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002208 try {
2209 return mContext.getPackageManager().getApplicationInfo(packageName,
2210 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2211 } catch (NameNotFoundException nnfe) {
2212 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002213 } finally {
2214 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002215 }
2216 }
2217
Fyodor Kupolov82402752015-10-28 14:54:51 -07002218 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002219 AtomicFile restrictionsFile =
2220 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2221 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002222 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002223 }
2224
2225 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002226 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002227 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002228 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002229 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002230 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002231 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002232
2233 FileInputStream fis = null;
2234 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002235 fis = restrictionsFile.openRead();
2236 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002237 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002238 XmlUtils.nextElement(parser);
2239 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002240 Slog.e(LOG_TAG, "Unable to read restrictions file "
2241 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002242 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002243 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002244 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2245 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002246 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002247 } catch (IOException|XmlPullParserException e) {
2248 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002249 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002250 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002251 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002252 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002253 }
2254
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002255 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2256 XmlPullParser parser) throws XmlPullParserException, IOException {
2257 int type = parser.getEventType();
2258 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2259 String key = parser.getAttributeValue(null, ATTR_KEY);
2260 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2261 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2262 if (multiple != null) {
2263 values.clear();
2264 int count = Integer.parseInt(multiple);
2265 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2266 if (type == XmlPullParser.START_TAG
2267 && parser.getName().equals(TAG_VALUE)) {
2268 values.add(parser.nextText().trim());
2269 count--;
2270 }
2271 }
2272 String [] valueStrings = new String[values.size()];
2273 values.toArray(valueStrings);
2274 restrictions.putStringArray(key, valueStrings);
2275 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2276 restrictions.putBundle(key, readBundleEntry(parser, values));
2277 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2278 final int outerDepth = parser.getDepth();
2279 ArrayList<Bundle> bundleList = new ArrayList<>();
2280 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2281 Bundle childBundle = readBundleEntry(parser, values);
2282 bundleList.add(childBundle);
2283 }
2284 restrictions.putParcelableArray(key,
2285 bundleList.toArray(new Bundle[bundleList.size()]));
2286 } else {
2287 String value = parser.nextText().trim();
2288 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2289 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2290 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2291 restrictions.putInt(key, Integer.parseInt(value));
2292 } else {
2293 restrictions.putString(key, value);
2294 }
2295 }
2296 }
2297 }
2298
2299 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2300 throws IOException, XmlPullParserException {
2301 Bundle childBundle = new Bundle();
2302 final int outerDepth = parser.getDepth();
2303 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2304 readEntry(childBundle, values, parser);
2305 }
2306 return childBundle;
2307 }
2308
Fyodor Kupolov82402752015-10-28 14:54:51 -07002309 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002310 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002311 AtomicFile restrictionsFile = new AtomicFile(
2312 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002313 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002314 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002315 }
2316
2317 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002318 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002319 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002320 try {
2321 fos = restrictionsFile.startWrite();
2322 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2323
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002324 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002325 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002326 serializer.startDocument(null, true);
2327 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2328
2329 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002330 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002331 serializer.endTag(null, TAG_RESTRICTIONS);
2332
2333 serializer.endDocument();
2334 restrictionsFile.finishWrite(fos);
2335 } catch (Exception e) {
2336 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002337 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2338 }
2339 }
2340
2341 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2342 throws IOException {
2343 for (String key : restrictions.keySet()) {
2344 Object value = restrictions.get(key);
2345 serializer.startTag(null, TAG_ENTRY);
2346 serializer.attribute(null, ATTR_KEY, key);
2347
2348 if (value instanceof Boolean) {
2349 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2350 serializer.text(value.toString());
2351 } else if (value instanceof Integer) {
2352 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2353 serializer.text(value.toString());
2354 } else if (value == null || value instanceof String) {
2355 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2356 serializer.text(value != null ? (String) value : "");
2357 } else if (value instanceof Bundle) {
2358 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2359 writeBundle((Bundle) value, serializer);
2360 } else if (value instanceof Parcelable[]) {
2361 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2362 Parcelable[] array = (Parcelable[]) value;
2363 for (Parcelable parcelable : array) {
2364 if (!(parcelable instanceof Bundle)) {
2365 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2366 }
2367 serializer.startTag(null, TAG_ENTRY);
2368 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2369 writeBundle((Bundle) parcelable, serializer);
2370 serializer.endTag(null, TAG_ENTRY);
2371 }
2372 } else {
2373 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2374 String[] values = (String[]) value;
2375 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2376 for (String choice : values) {
2377 serializer.startTag(null, TAG_VALUE);
2378 serializer.text(choice != null ? choice : "");
2379 serializer.endTag(null, TAG_VALUE);
2380 }
2381 }
2382 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002383 }
2384 }
2385
2386 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002387 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002388 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002389 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002390 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002391 }
2392 }
2393
2394 @Override
2395 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002396 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002397 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002398 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002399 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002400 }
2401 // Not found
2402 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002403 }
2404 }
2405
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002406 @Override
2407 public long getUserCreationTime(int userHandle) {
2408 int callingUserId = UserHandle.getCallingUserId();
2409 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002410 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002411 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002412 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002413 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002414 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002415 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002416 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002417 }
2418 }
2419 }
2420 if (userInfo == null) {
2421 throw new SecurityException("userHandle can only be the calling user or a managed "
2422 + "profile associated with this user");
2423 }
2424 return userInfo.creationTime;
2425 }
2426
Amith Yamasani0b285492011-04-14 17:35:23 -07002427 /**
2428 * Caches the list of user ids in an array, adjusting the array size when necessary.
2429 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002430 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002431 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002432 synchronized (mUsersLock) {
2433 final int userSize = mUsers.size();
2434 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002435 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002436 num++;
2437 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002438 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002439 final int[] newUsers = new int[num];
2440 int n = 0;
2441 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002442 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002443 newUsers[n++] = mUsers.keyAt(i);
2444 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002445 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002446 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002447 }
2448 }
2449
2450 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002451 * Called right before a user is started. This gives us a chance to prepare
2452 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002453 */
2454 public void onBeforeStartUser(int userId) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002455 mPm.reconcileAppsData(userId, Installer.FLAG_DE_STORAGE);
2456
2457 if (userId != UserHandle.USER_SYSTEM) {
2458 synchronized (mRestrictionsLock) {
2459 applyUserRestrictionsLR(userId);
2460 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002461 }
2462 }
2463
2464 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002465 * Called right before a user is unlocked. This gives us a chance to prepare
2466 * app storage.
2467 */
2468 public void onBeforeUnlockUser(int userId) {
2469 mPm.reconcileAppsData(userId, Installer.FLAG_CE_STORAGE);
2470 }
2471
2472 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002473 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002474 * @param userId the user that was just foregrounded
2475 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002476 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002477 UserData userData = getUserDataNoChecks(userId);
2478 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002479 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2480 return;
2481 }
2482 long now = System.currentTimeMillis();
2483 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002484 userData.info.lastLoggedInTime = now;
2485 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002486 }
2487 }
2488
2489 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002490 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002491 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2492 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002493 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002494 private int getNextAvailableId() {
2495 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002496 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002497 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002498 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002499 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002500 }
2501 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002502 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002503 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002504 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002505 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002506
Amith Yamasanifc95e702013-09-26 13:20:17 -07002507 private String packageToRestrictionsFileName(String packageName) {
2508 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2509 }
2510
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002511 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002512 * Enforce that serial number stored in user directory inode matches the
2513 * given expected value. Gracefully sets the serial number if currently
2514 * undefined.
2515 *
2516 * @throws IOException when problem extracting serial number, or serial
2517 * number is mismatched.
2518 */
2519 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2520 final int foundSerial = getSerialNumber(file);
2521 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2522
2523 if (foundSerial == -1) {
2524 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2525 try {
2526 setSerialNumber(file, serialNumber);
2527 } catch (IOException e) {
2528 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2529 }
2530
2531 } else if (foundSerial != serialNumber) {
2532 throw new IOException("Found serial number " + foundSerial
2533 + " doesn't match expected " + serialNumber);
2534 }
2535 }
2536
2537 /**
2538 * Set serial number stored in user directory inode.
2539 *
2540 * @throws IOException if serial number was already set
2541 */
2542 private static void setSerialNumber(File file, int serialNumber)
2543 throws IOException {
2544 try {
2545 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2546 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2547 } catch (ErrnoException e) {
2548 throw e.rethrowAsIOException();
2549 }
2550 }
2551
2552 /**
2553 * Return serial number stored in user directory inode.
2554 *
2555 * @return parsed serial number, or -1 if not set
2556 */
2557 private static int getSerialNumber(File file) throws IOException {
2558 try {
2559 final byte[] buf = new byte[256];
2560 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2561 final String serial = new String(buf, 0, len);
2562 try {
2563 return Integer.parseInt(serial);
2564 } catch (NumberFormatException e) {
2565 throw new IOException("Bad serial number: " + serial);
2566 }
2567 } catch (ErrnoException e) {
2568 if (e.errno == OsConstants.ENODATA) {
2569 return -1;
2570 } else {
2571 throw e.rethrowAsIOException();
2572 }
2573 }
2574 }
2575
Amith Yamasani920ace02012-09-20 22:15:37 -07002576 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002577 public void setSeedAccountData(int userId, String accountName, String accountType,
2578 PersistableBundle accountOptions, boolean persist) {
2579 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2580 synchronized (mPackagesLock) {
2581 final UserData userData;
2582 synchronized (mUsersLock) {
2583 userData = getUserDataLU(userId);
2584 if (userData == null) {
2585 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2586 return;
2587 }
2588 userData.seedAccountName = accountName;
2589 userData.seedAccountType = accountType;
2590 userData.seedAccountOptions = accountOptions;
2591 userData.persistSeedData = persist;
2592 }
2593 if (persist) {
2594 writeUserLP(userData);
2595 }
2596 }
2597 }
2598
2599 @Override
2600 public String getSeedAccountName() throws RemoteException {
2601 checkManageUsersPermission("Cannot get seed account information");
2602 synchronized (mUsersLock) {
2603 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2604 return userData.seedAccountName;
2605 }
2606 }
2607
2608 @Override
2609 public String getSeedAccountType() throws RemoteException {
2610 checkManageUsersPermission("Cannot get seed account information");
2611 synchronized (mUsersLock) {
2612 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2613 return userData.seedAccountType;
2614 }
2615 }
2616
2617 @Override
2618 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2619 checkManageUsersPermission("Cannot get seed account information");
2620 synchronized (mUsersLock) {
2621 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2622 return userData.seedAccountOptions;
2623 }
2624 }
2625
2626 @Override
2627 public void clearSeedAccountData() throws RemoteException {
2628 checkManageUsersPermission("Cannot clear seed account information");
2629 synchronized (mPackagesLock) {
2630 UserData userData;
2631 synchronized (mUsersLock) {
2632 userData = getUserDataLU(UserHandle.getCallingUserId());
2633 if (userData == null) return;
2634 userData.clearSeedAccountData();
2635 }
2636 writeUserLP(userData);
2637 }
2638 }
2639
2640 @Override
2641 public boolean someUserHasSeedAccount(String accountName, String accountType)
2642 throws RemoteException {
2643 checkManageUsersPermission("Cannot check seed account information");
2644 synchronized (mUsersLock) {
2645 final int userSize = mUsers.size();
2646 for (int i = 0; i < userSize; i++) {
2647 final UserData data = mUsers.valueAt(i);
2648 if (data.info.isInitialized()) continue;
2649 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2650 continue;
2651 }
2652 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2653 continue;
2654 }
2655 return true;
2656 }
2657 }
2658 return false;
2659 }
2660
2661 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002662 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2663 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2664 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2665 }
2666
2667 int onShellCommand(Shell shell, String cmd) {
2668 if (cmd == null) {
2669 return shell.handleDefaultCommands(cmd);
2670 }
2671
2672 final PrintWriter pw = shell.getOutPrintWriter();
2673 try {
2674 switch(cmd) {
2675 case "list":
2676 return runList(pw);
2677 }
2678 } catch (RemoteException e) {
2679 pw.println("Remote exception: " + e);
2680 }
2681 return -1;
2682 }
2683
2684 private int runList(PrintWriter pw) throws RemoteException {
2685 final IActivityManager am = ActivityManagerNative.getDefault();
2686 final List<UserInfo> users = getUsers(false);
2687 if (users == null) {
2688 pw.println("Error: couldn't get users");
2689 return 1;
2690 } else {
2691 pw.println("Users:");
2692 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002693 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002694 pw.println("\t" + users.get(i).toString() + running);
2695 }
2696 return 0;
2697 }
2698 }
2699
2700 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002701 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2702 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2703 != PackageManager.PERMISSION_GRANTED) {
2704 pw.println("Permission Denial: can't dump UserManager from from pid="
2705 + Binder.getCallingPid()
2706 + ", uid=" + Binder.getCallingUid()
2707 + " without permission "
2708 + android.Manifest.permission.DUMP);
2709 return;
2710 }
2711
2712 long now = System.currentTimeMillis();
2713 StringBuilder sb = new StringBuilder();
2714 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002715 synchronized (mUsersLock) {
2716 pw.println("Users:");
2717 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002718 UserData userData = mUsers.valueAt(i);
2719 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002720 continue;
2721 }
Amith Yamasani12747872015-12-07 14:19:49 -08002722 UserInfo userInfo = userData.info;
2723 final int userId = userInfo.id;
2724 pw.print(" "); pw.print(userInfo);
2725 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002726 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002727 pw.print(" <removing> ");
2728 }
Amith Yamasani12747872015-12-07 14:19:49 -08002729 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002730 pw.print(" <partial>");
2731 }
2732 pw.println();
2733 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002734 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002735 pw.println("<unknown>");
2736 } else {
2737 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002738 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002739 sb.append(" ago");
2740 pw.println(sb);
2741 }
2742 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002743 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002744 pw.println("<unknown>");
2745 } else {
2746 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002747 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002748 sb.append(" ago");
2749 pw.println(sb);
2750 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002751 pw.print(" Has profile owner: ");
2752 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002753 pw.println(" Restrictions:");
2754 synchronized (mRestrictionsLock) {
2755 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002756 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002757 pw.println(" Device policy local restrictions:");
2758 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002759 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002760 pw.println(" Effective restrictions:");
2761 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002762 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002763 }
Amith Yamasani12747872015-12-07 14:19:49 -08002764
2765 if (userData.account != null) {
2766 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002767 pw.println();
2768 }
Amith Yamasani12747872015-12-07 14:19:49 -08002769
2770 if (userData.seedAccountName != null) {
2771 pw.print(" Seed account name: " + userData.seedAccountName);
2772 pw.println();
2773 if (userData.seedAccountType != null) {
2774 pw.print(" account type: " + userData.seedAccountType);
2775 pw.println();
2776 }
2777 if (userData.seedAccountOptions != null) {
2778 pw.print(" account options exist");
2779 pw.println();
2780 }
2781 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002782 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002783 }
Amith Yamasani12747872015-12-07 14:19:49 -08002784 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002785 pw.println(" Device policy global restrictions:");
2786 synchronized (mRestrictionsLock) {
2787 UserRestrictionsUtils
2788 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2789 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002790 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002791 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002792 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002793 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002794 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002795 synchronized (mUsersLock) {
2796 pw.println();
2797 pw.println(" Device managed: " + mIsDeviceManaged);
2798 }
Amith Yamasani12747872015-12-07 14:19:49 -08002799 // Dump some capabilities
2800 pw.println();
2801 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2802 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Amith Yamasani920ace02012-09-20 22:15:37 -07002803 }
2804 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002805
2806 final class MainHandler extends Handler {
2807
2808 @Override
2809 public void handleMessage(Message msg) {
2810 switch (msg.what) {
2811 case WRITE_USER_MSG:
2812 removeMessages(WRITE_USER_MSG, msg.obj);
2813 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002814 int userId = ((UserData) msg.obj).info.id;
2815 UserData userData = getUserDataNoChecks(userId);
2816 if (userData != null) {
2817 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002818 }
2819 }
2820 }
2821 }
2822 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002823
2824 /**
2825 * @param userId
2826 * @return whether the user has been initialized yet
2827 */
2828 boolean isInitialized(int userId) {
2829 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2830 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002831
2832 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002833 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002834 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2835 @Nullable Bundle globalRestrictions) {
2836 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2837 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002838 }
2839
2840 @Override
2841 public Bundle getBaseUserRestrictions(int userId) {
2842 synchronized (mRestrictionsLock) {
2843 return mBaseUserRestrictions.get(userId);
2844 }
2845 }
2846
2847 @Override
2848 public void setBaseUserRestrictionsByDpmsForMigration(
2849 int userId, Bundle baseRestrictions) {
2850 synchronized (mRestrictionsLock) {
2851 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002852 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002853 }
2854
Amith Yamasani12747872015-12-07 14:19:49 -08002855 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002856 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002857 if (userData != null) {
2858 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002859 } else {
2860 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2861 }
2862 }
2863 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002864
2865 @Override
2866 public boolean getUserRestriction(int userId, String key) {
2867 return getUserRestrictions(userId).getBoolean(key);
2868 }
2869
2870 @Override
2871 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2872 synchronized (mUserRestrictionsListeners) {
2873 mUserRestrictionsListeners.add(listener);
2874 }
2875 }
2876
2877 @Override
2878 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2879 synchronized (mUserRestrictionsListeners) {
2880 mUserRestrictionsListeners.remove(listener);
2881 }
2882 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002883
2884 @Override
2885 public void setDeviceManaged(boolean isManaged) {
2886 synchronized (mUsersLock) {
2887 mIsDeviceManaged = isManaged;
2888 }
2889 }
2890
2891 @Override
2892 public void setUserManaged(int userId, boolean isManaged) {
2893 synchronized (mUsersLock) {
2894 mIsUserManaged.put(userId, isManaged);
2895 }
2896 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002897 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002898
2899 private class Shell extends ShellCommand {
2900 @Override
2901 public int onCommand(String cmd) {
2902 return onShellCommand(this, cmd);
2903 }
2904
2905 @Override
2906 public void onHelp() {
2907 final PrintWriter pw = getOutPrintWriter();
2908 pw.println("User manager (user) commands:");
2909 pw.println(" help");
2910 pw.println(" Print this help text.");
2911 pw.println("");
2912 pw.println(" list");
2913 pw.println(" Prints all users on the system.");
2914 }
2915 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002916
2917 private static void debug(String message) {
2918 Log.d(LOG_TAG, message +
2919 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2920 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002921}