blob: b31d731e46b931e7111aa494bbca0fcf90887723 [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 Chen594f2082015-08-18 11:04:20 -070019import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070020import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070023import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070024import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070025import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070026import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070027import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070028import android.content.Context;
29import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070030import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070031import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080032import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070034import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080037import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070038import android.os.Environment;
39import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080040import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080042import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010043import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070044import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070046import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070047import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040048import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070049import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070050import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070051import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070052import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080053import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010054import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070055import android.os.storage.VolumeInfo;
56import android.system.ErrnoException;
57import android.system.Os;
58import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070059import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070060import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070061import android.util.Slog;
62import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080063import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070064import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import android.util.Xml;
66
Makoto Onuki068c54a2015-10-13 14:34:03 -070067import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070068import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040069import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080070import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070071import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070072import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070073import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080074
75import org.xmlpull.v1.XmlPullParser;
76import org.xmlpull.v1.XmlPullParserException;
77import org.xmlpull.v1.XmlSerializer;
78
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import java.io.BufferedOutputStream;
80import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070081import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070083import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084import java.io.FileOutputStream;
85import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070086import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010087import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088import java.util.ArrayList;
89import java.util.List;
90
Fyodor Kupolov262f9952015-03-23 18:55:11 -070091import libcore.io.IoUtils;
92
Makoto Onuki068c54a2015-10-13 14:34:03 -070093/**
94 * Service for {@link UserManager}.
95 *
96 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -070097 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -080098 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -070099 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
100 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
101 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700102 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700103public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700104 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800105 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
106 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700107
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700110 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700112 private static final String ATTR_CREATION_TIME = "created";
113 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700114 private static final String ATTR_SERIAL_NO = "serialNumber";
115 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700116 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700117 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700118 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100119 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700120 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530121 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800124 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800125 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800126 private static final String TAG_ENTRY = "entry";
127 private static final String TAG_VALUE = "value";
128 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700129 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800130 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700131
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700132 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
133 private static final String ATTR_TYPE_STRING = "s";
134 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700135 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700136 private static final String ATTR_TYPE_BUNDLE = "B";
137 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700138
Amith Yamasani0b285492011-04-14 17:35:23 -0700139 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700140 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700141 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100142 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800144 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700145 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800146
Amith Yamasani634cf312012-10-04 17:34:21 -0700147 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700148 // We need to keep process uid within Integer.MAX_VALUE.
149 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700150
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700151 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700152
Amith Yamasani920ace02012-09-20 22:15:37 -0700153 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
154
Nicolas Prevotb8186812015-08-06 15:00:03 +0100155 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700156 // without first making sure that the rest of the framework is prepared for it.
157 private static final int MAX_MANAGED_PROFILES = 1;
158
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800159 static final int WRITE_USER_MSG = 1;
160 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530161
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700162 private static final String XATTR_SERIAL = "user.serial";
163
Dianne Hackborn4428e172012-08-24 17:43:05 -0700164 private final Context mContext;
165 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700166 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700167 // Short-term lock for internal state, when interaction/sync with PM is not required
168 private final Object mUsersLock = new Object();
169 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700170
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800171 private final Handler mHandler;
172
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700173 private final File mUsersDir;
174 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700175
Fyodor Kupolov82402752015-10-28 14:54:51 -0700176 @GuardedBy("mUsersLock")
177 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700178
179 /**
180 * User restrictions set via UserManager. This doesn't include restrictions set by
181 * device owner / profile owners.
182 *
183 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
184 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
185 * maybe shared between {@link #mBaseUserRestrictions} and
186 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
187 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700188 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700189 */
190 @GuardedBy("mRestrictionsLock")
191 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
192
193 /**
194 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
195 * with device / profile owner restrictions. We'll initialize it lazily; use
196 * {@link #getEffectiveUserRestrictions} to access it.
197 *
198 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
199 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
200 * maybe shared between {@link #mBaseUserRestrictions} and
201 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
202 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700203 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700204 */
205 @GuardedBy("mRestrictionsLock")
206 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
207
Makoto Onuki4f160732015-10-27 17:15:38 -0700208 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800209 * User restrictions that have already been applied in
210 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
211 * that have changed since the last
212 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700213 */
214 @GuardedBy("mRestrictionsLock")
215 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
216
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800217 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800218 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
219 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800220 */
221 @GuardedBy("mRestrictionsLock")
222 private Bundle mDevicePolicyGlobalUserRestrictions;
223
224 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800225 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
226 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800227 */
228 @GuardedBy("mRestrictionsLock")
229 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
230
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800231 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530232 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800233
234 /**
235 * Set of user IDs being actively removed. Removed IDs linger in this set
236 * for several seconds to work around a VFS caching issue.
237 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700238 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800239 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700240
Fyodor Kupolov82402752015-10-28 14:54:51 -0700241 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700242 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800243 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700244 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700245 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700246
Jason Monk62062992014-05-06 09:55:28 -0400247 private IAppOpsService mAppOpsService;
248
Makoto Onuki068c54a2015-10-13 14:34:03 -0700249 private final LocalService mLocalService;
250
Makoto Onukie7927da2015-11-25 10:05:17 -0800251 @GuardedBy("mUsersLock")
252 private boolean mIsDeviceManaged;
253
254 @GuardedBy("mUsersLock")
255 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
256
Makoto Onukid45a4a22015-11-02 17:17:38 -0800257 @GuardedBy("mUserRestrictionsListeners")
258 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
259 new ArrayList<>();
260
Amith Yamasani258848d2012-08-10 17:06:33 -0700261 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700262
Dianne Hackborn4428e172012-08-24 17:43:05 -0700263 public static UserManagerService getInstance() {
264 synchronized (UserManagerService.class) {
265 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700266 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700267 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700268
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800269 @VisibleForTesting
270 UserManagerService(File dataDir) {
271 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700272 }
273
Dianne Hackborn4428e172012-08-24 17:43:05 -0700274 /**
275 * Called by package manager to create the service. This is closely
276 * associated with the package manager, and the given lock is the
277 * package manager's own lock.
278 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800279 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
280 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700281 }
282
Dianne Hackborn4428e172012-08-24 17:43:05 -0700283 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800284 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700285 mContext = context;
286 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700287 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800288 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800289 synchronized (mPackagesLock) {
290 mUsersDir = new File(dataDir, USER_INFO_DIR);
291 mUsersDir.mkdirs();
292 // Make zeroth user directory, for services to migrate their files to that location
293 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
294 userZeroDir.mkdirs();
295 FileUtils.setPermissions(mUsersDir.toString(),
296 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
297 -1, -1);
298 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
299 initDefaultGuestRestrictions();
300 readUserListLP();
301 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700302 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700303 mLocalService = new LocalService();
304 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700305 }
306
307 void systemReady() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800308 // Prune out any partially created/partially removed users.
309 ArrayList<UserInfo> partials = new ArrayList<>();
310 synchronized (mUsersLock) {
311 final int userSize = mUsers.size();
312 for (int i = 0; i < userSize; i++) {
313 UserInfo ui = mUsers.valueAt(i);
314 if ((ui.partial || ui.guestToRemove) && i != 0) {
315 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700316 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700317 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700318 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800319 final int partialsSize = partials.size();
320 for (int i = 0; i < partialsSize; i++) {
321 UserInfo ui = partials.get(i);
322 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
323 + " (name=" + ui.name + ")");
324 removeUserState(ui.id);
325 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800326
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700327 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800328
Jason Monk62062992014-05-06 09:55:28 -0400329 mAppOpsService = IAppOpsService.Stub.asInterface(
330 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800331
332 synchronized (mRestrictionsLock) {
333 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400334 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700335 }
336
337 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700338 public UserInfo getPrimaryUser() {
339 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700340 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700341 final int userSize = mUsers.size();
342 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700343 UserInfo ui = mUsers.valueAt(i);
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800344 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700345 return ui;
346 }
347 }
348 }
349 return null;
350 }
351
352 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700353 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700354 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700355 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700356 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700357 final int userSize = mUsers.size();
358 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700359 UserInfo ui = mUsers.valueAt(i);
360 if (ui.partial) {
361 continue;
362 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800363 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700364 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700365 }
Amith Yamasani13593602012-03-22 16:16:17 -0700366 }
367 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700368 }
Amith Yamasani13593602012-03-22 16:16:17 -0700369 }
370
Amith Yamasani258848d2012-08-10 17:06:33 -0700371 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100372 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800373 if (userId != UserHandle.getCallingUserId()) {
374 checkManageUsersPermission("getting profiles related to user " + userId);
375 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700376 final long ident = Binder.clearCallingIdentity();
377 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700378 synchronized (mUsersLock) {
379 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100380 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700381 } finally {
382 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000383 }
384 }
385
Amith Yamasanibe465322014-04-24 13:45:17 -0700386 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700387 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
388 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700389 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700390 if (user == null) {
391 // Probably a dying user
392 return users;
393 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700394 final int userSize = mUsers.size();
395 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700396 UserInfo profile = mUsers.valueAt(i);
397 if (!isProfileOf(user, profile)) {
398 continue;
399 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100400 if (enabledOnly && !profile.isEnabled()) {
401 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700402 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700403 if (mRemovingUserIds.get(profile.id)) {
404 continue;
405 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700406 users.add(profile);
407 }
408 return users;
409 }
410
Jessica Hummelbe81c802014-04-22 15:49:22 +0100411 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700412 public int getCredentialOwnerProfile(int userHandle) {
413 checkManageUsersPermission("get the credential owner");
Jeff Sharkeyba512352015-11-12 20:17:45 -0800414 if (!StorageManager.isFileBasedEncryptionEnabled()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700415 synchronized (mUsersLock) {
416 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700417 if (profileParent != null) {
418 return profileParent.id;
419 }
420 }
421 }
422
423 return userHandle;
424 }
425
426 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700427 public boolean isSameProfileGroup(int userId, int otherUserId) {
428 if (userId == otherUserId) return true;
429 checkManageUsersPermission("check if in the same profile group");
430 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700431 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700432 }
433 }
434
Fyodor Kupolov82402752015-10-28 14:54:51 -0700435 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
436 synchronized (mUsersLock) {
437 UserInfo userInfo = getUserInfoLU(userId);
438 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
439 return false;
440 }
441 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
442 if (otherUserInfo == null
443 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
444 return false;
445 }
446 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700447 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700448 }
449
450 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100451 public UserInfo getProfileParent(int userHandle) {
452 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700453 synchronized (mUsersLock) {
454 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700455 }
456 }
457
Fyodor Kupolov82402752015-10-28 14:54:51 -0700458 private UserInfo getProfileParentLU(int userHandle) {
459 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700460 if (profile == null) {
461 return null;
462 }
463 int parentUserId = profile.profileGroupId;
464 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
465 return null;
466 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700467 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100468 }
469 }
470
Fyodor Kupolov82402752015-10-28 14:54:51 -0700471 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100472 return user.id == profile.id ||
473 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
474 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000475 }
476
477 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100478 public void setUserEnabled(int userId) {
479 checkManageUsersPermission("enable user");
480 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700481 UserInfo info;
482 synchronized (mUsersLock) {
483 info = getUserInfoLU(userId);
484 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100485 if (info != null && !info.isEnabled()) {
486 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700487 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100488 }
489 }
490 }
491
492 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700493 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700494 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700495 synchronized (mUsersLock) {
496 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700497 }
498 }
499
Amith Yamasani71e6c692013-03-24 17:39:28 -0700500 @Override
501 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700502 synchronized (mUsersLock) {
503 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700504 }
505 }
506
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700507 @Override
508 public boolean canHaveRestrictedProfile(int userId) {
509 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700510 synchronized (mUsersLock) {
511 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700512 if (userInfo == null || !userInfo.canHaveProfile()) {
513 return false;
514 }
515 if (!userInfo.isAdmin()) {
516 return false;
517 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800518 // restricted profile can be created if there is no DO set and the admin user has no PO;
519 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700520 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700521 }
522
Amith Yamasani195263742012-08-21 15:40:12 -0700523 /*
524 * Should be locked on mUsers before calling this.
525 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700526 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700527 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700528 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800529 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700530 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
531 return null;
532 }
533 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700534 }
535
Fyodor Kupolov82402752015-10-28 14:54:51 -0700536 /**
537 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
538 * <p>No permissions checking or any addition checks are made</p>
539 */
540 private UserInfo getUserInfoNoChecks(int userId) {
541 synchronized (mUsersLock) {
542 return mUsers.get(userId);
543 }
544 }
545
Amith Yamasani236b2b52015-08-18 14:32:14 -0700546 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700547 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700548 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700549 }
550
Amith Yamasani258848d2012-08-10 17:06:33 -0700551 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700552 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700553 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700554 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700555 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700556 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700557 if (info == null || info.partial) {
558 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
559 return;
560 }
Amith Yamasani13593602012-03-22 16:16:17 -0700561 if (name != null && !name.equals(info.name)) {
562 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700563 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700564 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700565 }
566 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700567 if (changed) {
568 sendUserInfoChangedBroadcast(userId);
569 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700570 }
571
Amith Yamasani258848d2012-08-10 17:06:33 -0700572 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700573 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700574 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400575 long ident = Binder.clearCallingIdentity();
576 try {
577 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700578 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400579 if (info == null || info.partial) {
580 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
581 return;
582 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700583 writeBitmapLP(info, bitmap);
584 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700585 }
Jason Monk9a944532014-07-08 09:31:21 -0400586 sendUserInfoChangedBroadcast(userId);
587 } finally {
588 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700589 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700590 }
591
592 private void sendUserInfoChangedBroadcast(int userId) {
593 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
594 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
595 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700596 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700597 }
598
Amith Yamasani258848d2012-08-10 17:06:33 -0700599 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100600 public ParcelFileDescriptor getUserIcon(int userId) {
601 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700602 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700603 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700604 if (info == null || info.partial) {
605 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
606 return null;
607 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700608 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100609 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
610 || callingGroupId != info.profileGroupId) {
611 checkManageUsersPermission("get the icon of a user who is not related");
612 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700613 if (info.iconPath == null) {
614 return null;
615 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100616 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700617 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100618
619 try {
620 return ParcelFileDescriptor.open(
621 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
622 } catch (FileNotFoundException e) {
623 Log.e(LOG_TAG, "Couldn't find icon file", e);
624 }
625 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700626 }
627
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700628 public void makeInitialized(int userId) {
629 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800630 boolean scheduleWriteUser = false;
631 UserInfo info;
632 synchronized (mUsersLock) {
633 info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700634 if (info == null || info.partial) {
635 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800636 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700637 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800638 if ((info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700639 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800640 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700641 }
642 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800643 if (scheduleWriteUser) {
644 scheduleWriteUser(info);
645 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700646 }
647
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700648 /**
649 * If default guest restrictions haven't been initialized yet, add the basic
650 * restrictions.
651 */
652 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800653 synchronized (mGuestRestrictions) {
654 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800655 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800656 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
657 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
658 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700659 }
660 }
661
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800662 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530663 public Bundle getDefaultGuestRestrictions() {
664 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800665 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530666 return new Bundle(mGuestRestrictions);
667 }
668 }
669
670 @Override
671 public void setDefaultGuestRestrictions(Bundle restrictions) {
672 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800673 synchronized (mGuestRestrictions) {
674 mGuestRestrictions.clear();
675 mGuestRestrictions.putAll(restrictions);
676 }
677 synchronized (mPackagesLock) {
678 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530679 }
680 }
681
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800682 /**
683 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
684 */
685 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
686 @Nullable Bundle global) {
687 Preconditions.checkNotNull(local);
688 boolean globalChanged = false;
689 boolean localChanged;
690 synchronized (mRestrictionsLock) {
691 if (global != null) {
692 // Update global.
693 globalChanged = !UserRestrictionsUtils.areEqual(
694 mDevicePolicyGlobalUserRestrictions, global);
695 if (globalChanged) {
696 mDevicePolicyGlobalUserRestrictions = global;
697 }
698 }
699 {
700 // Update local.
701 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
702 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
703 if (localChanged) {
704 mDevicePolicyLocalUserRestrictions.put(userId, local);
705 }
706 }
707 }
708 if (DBG) {
709 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
710 + " global=" + global + (globalChanged ? " (changed)" : "")
711 + " local=" + local + (localChanged ? " (changed)" : "")
712 );
713 }
714 // Don't call them within the mRestrictionsLock.
715 synchronized (mPackagesLock) {
716 if (globalChanged) {
717 writeUserListLP();
718 }
719 if (localChanged) {
720 writeUserLP(getUserInfoNoChecks(userId));
721 }
722 }
723
724 synchronized (mRestrictionsLock) {
725 if (globalChanged) {
726 applyUserRestrictionsForAllUsersLR();
727 } else if (localChanged) {
728 applyUserRestrictionsLR(userId);
729 }
730 }
731 }
732
Makoto Onuki068c54a2015-10-13 14:34:03 -0700733 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700734 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800735 final Bundle baseRestrictions =
736 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
737 final Bundle global = mDevicePolicyGlobalUserRestrictions;
738 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700739
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800740 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
741 // Common case first.
742 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700743 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800744 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
745 UserRestrictionsUtils.merge(effective, global);
746 UserRestrictionsUtils.merge(effective, local);
747
Makoto Onuki068c54a2015-10-13 14:34:03 -0700748 return effective;
749 }
750
751 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700752 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700753 if (DBG) {
754 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
755 }
756 mCachedEffectiveUserRestrictions.remove(userId);
757 }
758
759 private Bundle getEffectiveUserRestrictions(int userId) {
760 synchronized (mRestrictionsLock) {
761 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
762 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700763 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700764 mCachedEffectiveUserRestrictions.put(userId, restrictions);
765 }
766 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700767 }
768 }
769
Makoto Onuki068c54a2015-10-13 14:34:03 -0700770 /** @return a specific user restriction that's in effect currently. */
771 @Override
772 public boolean hasUserRestriction(String restrictionKey, int userId) {
773 Bundle restrictions = getEffectiveUserRestrictions(userId);
774 return restrictions != null && restrictions.getBoolean(restrictionKey);
775 }
776
777 /**
778 * @return UserRestrictions that are in effect currently. This always returns a new
779 * {@link Bundle}.
780 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700781 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800782 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800783 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800784 }
785
786 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700787 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700788 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700789 synchronized (mRestrictionsLock) {
790 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
791 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800792 final Bundle newRestrictions = UserRestrictionsUtils.clone(
793 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700794 newRestrictions.putBoolean(key, value);
795
Fyodor Kupolov82402752015-10-28 14:54:51 -0700796 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700797 }
798 }
799
Makoto Onuki068c54a2015-10-13 14:34:03 -0700800 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800801 * Optionally updating user restrictions, calculate the effective user restrictions and also
802 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700803 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800804 * @param newRestrictions User restrictions to set.
805 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700806 * @param userId target user ID.
807 */
808 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700809 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700810 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800811
812 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
813 mAppliedUserRestrictions.get(userId));
814
815 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700816 if (newRestrictions != null) {
817 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800818 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
819
820 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700821 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
822 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800823
824 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
825 mBaseUserRestrictions.put(userId, newRestrictions);
826 scheduleWriteUser(getUserInfoNoChecks(userId));
827 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700828 }
829
Fyodor Kupolov82402752015-10-28 14:54:51 -0700830 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700831
Makoto Onuki759a7632015-10-28 16:43:10 -0700832 mCachedEffectiveUserRestrictions.put(userId, effective);
833
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800834 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700835 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800836 debug("Applying user restrictions: userId=" + userId
837 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700838 }
839
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800840 if (mAppOpsService != null) { // We skip it until system-ready.
841 final long token = Binder.clearCallingIdentity();
842 try {
843 mAppOpsService.setUserRestrictions(effective, userId);
844 } catch (RemoteException e) {
845 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
846 } finally {
847 Binder.restoreCallingIdentity(token);
848 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700849 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700850
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800851 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700852
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800853 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700854 }
855
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800856 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800857 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800858 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
859 // actually, but we still need some kind of synchronization otherwise we might end up
860 // calling listeners out-of-order, thus "LR".
861
862 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
863 return;
864 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800865
866 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
867 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
868
869 mHandler.post(new Runnable() {
870 @Override
871 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700872 UserRestrictionsUtils.applyUserRestrictions(
873 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800874
Makoto Onukid45a4a22015-11-02 17:17:38 -0800875 final UserRestrictionsListener[] listeners;
876 synchronized (mUserRestrictionsListeners) {
877 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
878 mUserRestrictionsListeners.toArray(listeners);
879 }
880 for (int i = 0; i < listeners.length; i++) {
881 listeners[i].onUserRestrictionsChanged(userId,
882 newRestrictionsFinal, prevRestrictionsFinal);
883 }
884 }
885 });
886 }
887
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800888 // Package private for the inner class.
889 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700890 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700891 }
892
893 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800894 // Package private for the inner class.
895 void applyUserRestrictionsForAllUsersLR() {
896 if (DBG) {
897 debug("applyUserRestrictionsForAllUsersLR");
898 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700899 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700900 mCachedEffectiveUserRestrictions.clear();
901
Makoto Onuki068c54a2015-10-13 14:34:03 -0700902 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
903 // it on a handler.
904 final Runnable r = new Runnable() {
905 @Override
906 public void run() {
907 // Then get the list of running users.
908 final int[] runningUsers;
909 try {
910 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
911 } catch (RemoteException e) {
912 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
913 return;
914 }
915 // Then re-calculate the effective restrictions and apply, only for running users.
916 // It's okay if a new user has started after the getRunningUserIds() call,
917 // because we'll do the same thing (re-calculate the restrictions and apply)
918 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700919 synchronized (mRestrictionsLock) {
920 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800921 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700922 }
923 }
924 }
925 };
926 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700927 }
928
Amith Yamasani258848d2012-08-10 17:06:33 -0700929 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700930 * Check if we've hit the limit of how many users can be created.
931 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700932 private boolean isUserLimitReached() {
933 int count;
934 synchronized (mUsersLock) {
935 count = getAliveUsersExcludingGuestsCountLU();
936 }
937 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700938 }
939
940 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000941 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700942 checkManageUsersPermission("check if more managed profiles can be added.");
943 if (ActivityManager.isLowRamDeviceStatic()) {
944 return false;
945 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700946 if (!mContext.getPackageManager().hasSystemFeature(
947 PackageManager.FEATURE_MANAGED_USERS)) {
948 return false;
949 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100950 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000951 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
952 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
953 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100954 return false;
955 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700956 synchronized(mUsersLock) {
957 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100958 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700959 return false;
960 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000961 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
962 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -0700963 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000964 return usersCountAfterRemoving == 1
965 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700966 }
967 }
968
Fyodor Kupolov82402752015-10-28 14:54:51 -0700969 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700970 int aliveUserCount = 0;
971 final int totalUserCount = mUsers.size();
972 // Skip over users being removed
973 for (int i = 0; i < totalUserCount; i++) {
974 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700975 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700976 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700977 aliveUserCount++;
978 }
979 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700980 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700981 }
982
983 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700984 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700985 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700986 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700987 *
988 * @param message used as message if SecurityException is thrown
989 * @throws SecurityException if the caller is not system or root
990 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700991 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700992 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700993 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400994 && ActivityManager.checkComponentPermission(
995 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700996 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
997 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
998 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400999 }
1000
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001001 private static void checkSystemOrRoot(String message) {
1002 final int uid = Binder.getCallingUid();
1003 if (uid != Process.SYSTEM_UID && uid != 0) {
1004 throw new SecurityException("Only system may call: " + message);
1005 }
1006 }
1007
Fyodor Kupolov82402752015-10-28 14:54:51 -07001008 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001009 try {
1010 File dir = new File(mUsersDir, Integer.toString(info.id));
1011 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001012 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001013 if (!dir.exists()) {
1014 dir.mkdir();
1015 FileUtils.setPermissions(
1016 dir.getPath(),
1017 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1018 -1, -1);
1019 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001020 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001021 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1022 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001023 info.iconPath = file.getAbsolutePath();
1024 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001025 try {
1026 os.close();
1027 } catch (IOException ioe) {
1028 // What the ... !
1029 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001030 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001031 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001032 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001033 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001034 }
1035
Amith Yamasani0b285492011-04-14 17:35:23 -07001036 /**
1037 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1038 * cache it elsewhere.
1039 * @return the array of user ids.
1040 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001041 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001042 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001043 return mUserIds;
1044 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001045 }
1046
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001047 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001048 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001049 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001050 return;
1051 }
1052 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001053 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001054 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001055 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001056 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001057 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001058 int type;
1059 while ((type = parser.next()) != XmlPullParser.START_TAG
1060 && type != XmlPullParser.END_DOCUMENT) {
1061 ;
1062 }
1063
1064 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001065 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001066 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001067 return;
1068 }
1069
Amith Yamasani2a003292012-08-14 18:25:45 -07001070 mNextSerialNumber = -1;
1071 if (parser.getName().equals(TAG_USERS)) {
1072 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1073 if (lastSerialNumber != null) {
1074 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1075 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001076 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1077 if (versionNumber != null) {
1078 mUserVersion = Integer.parseInt(versionNumber);
1079 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001080 }
1081
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001082 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1083
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001084 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301085 if (type == XmlPullParser.START_TAG) {
1086 final String name = parser.getName();
1087 if (name.equals(TAG_USER)) {
1088 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001089 UserInfo user = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001090
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301091 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001092 synchronized (mUsersLock) {
1093 mUsers.put(user.id, user);
1094 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1095 mNextSerialNumber = user.id + 1;
1096 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301097 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001098 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301099 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001100 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1101 && type != XmlPullParser.END_TAG) {
1102 if (type == XmlPullParser.START_TAG) {
1103 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001104 synchronized (mGuestRestrictions) {
1105 UserRestrictionsUtils
1106 .readRestrictions(parser, mGuestRestrictions);
1107 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001108 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1109 ) {
1110 UserRestrictionsUtils.readRestrictions(parser,
1111 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001112 }
1113 break;
1114 }
1115 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001116 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001117 }
1118 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001119 synchronized (mRestrictionsLock) {
1120 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1121 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001122 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001123 upgradeIfNecessaryLP();
1124 } catch (IOException | XmlPullParserException e) {
1125 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001126 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001127 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001128 }
1129 }
1130
Amith Yamasani6f34b412012-10-22 18:19:27 -07001131 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001132 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001133 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001134 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001135 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001136 int userVersion = mUserVersion;
1137 if (userVersion < 1) {
1138 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001139 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001140 if ("Primary".equals(user.name)) {
1141 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001142 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001143 }
1144 userVersion = 1;
1145 }
1146
Amith Yamasanibc9625052012-11-15 14:39:18 -08001147 if (userVersion < 2) {
1148 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001149 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001150 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1151 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001152 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001153 }
1154 userVersion = 2;
1155 }
1156
Amith Yamasani350962c2013-08-06 11:18:53 -07001157
Amith Yamasani5e486f52013-08-07 11:06:44 -07001158 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001159 userVersion = 4;
1160 }
1161
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001162 if (userVersion < 5) {
1163 initDefaultGuestRestrictions();
1164 userVersion = 5;
1165 }
1166
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001167 if (userVersion < 6) {
1168 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001169 synchronized (mUsersLock) {
1170 for (int i = 0; i < mUsers.size(); i++) {
1171 UserInfo user = mUsers.valueAt(i);
1172 // In non-split mode, only user 0 can have restricted profiles
1173 if (!splitSystemUser && user.isRestricted()
1174 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1175 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001176 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001177 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001178 }
1179 }
1180 userVersion = 6;
1181 }
1182
Amith Yamasani6f34b412012-10-22 18:19:27 -07001183 if (userVersion < USER_VERSION) {
1184 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1185 + USER_VERSION);
1186 } else {
1187 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001188
1189 if (originalVersion < mUserVersion) {
1190 writeUserListLP();
1191 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001192 }
1193 }
1194
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001195 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001196 int flags = UserInfo.FLAG_INITIALIZED;
1197 // In split system user mode, the admin and primary flags are assigned to the first human
1198 // user.
1199 if (!UserManager.isSplitSystemUser()) {
1200 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1201 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001202 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001203 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001204 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001205 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001206 synchronized (mUsersLock) {
1207 mUsers.put(system.id, system);
1208 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001209 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001210 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001211
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001212 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001213 synchronized (mRestrictionsLock) {
1214 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1215 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001216
Fyodor Kupolov82402752015-10-28 14:54:51 -07001217 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001218 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001219
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001220 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001221 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001222 }
1223
Makoto Onuki9e935a32015-11-06 14:24:24 -08001224 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001225 if (DBG) {
1226 debug("scheduleWriteUser");
1227 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001228 // No need to wrap it within a lock -- worst case, we'll just post the same message
1229 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001230 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1231 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1232 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1233 }
1234 }
1235
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001236 /*
1237 * Writes the user file in this format:
1238 *
1239 * <user flags="20039023" id="0">
1240 * <name>Primary</name>
1241 * </user>
1242 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001243 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001244 if (DBG) {
1245 debug("writeUserLP " + userInfo);
1246 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001247 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001248 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001249 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001250 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001251 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1252
1253 // XmlSerializer serializer = XmlUtils.serializerInstance();
1254 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001255 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001256 serializer.startDocument(null, true);
1257 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1258
1259 serializer.startTag(null, TAG_USER);
1260 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001261 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001262 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001263 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1264 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1265 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001266 if (userInfo.iconPath != null) {
1267 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1268 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001269 if (userInfo.partial) {
1270 serializer.attribute(null, ATTR_PARTIAL, "true");
1271 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001272 if (userInfo.guestToRemove) {
1273 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1274 }
Kenny Guy2a764942014-04-02 13:29:20 +01001275 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1276 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1277 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001278 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001279 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1280 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1281 Integer.toString(userInfo.restrictedProfileParentId));
1282 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001283 serializer.startTag(null, TAG_NAME);
1284 serializer.text(userInfo.name);
1285 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001286 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001287 UserRestrictionsUtils.writeRestrictions(serializer,
1288 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1289 UserRestrictionsUtils.writeRestrictions(serializer,
1290 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1291 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001292 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001293 serializer.endTag(null, TAG_USER);
1294
1295 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001296 userFile.finishWrite(fos);
1297 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001298 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001299 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001300 }
1301 }
1302
1303 /*
1304 * Writes the user list file in this format:
1305 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001306 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001307 * <user id="0"></user>
1308 * <user id="2"></user>
1309 * </users>
1310 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001311 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001312 if (DBG) {
1313 debug("writeUserList");
1314 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001315 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001316 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001317 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001318 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001319 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1320
1321 // XmlSerializer serializer = XmlUtils.serializerInstance();
1322 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001323 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001324 serializer.startDocument(null, true);
1325 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1326
1327 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001328 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001329 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001330
Adam Lesinskieddeb492014-09-08 17:50:03 -07001331 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001332 synchronized (mGuestRestrictions) {
1333 UserRestrictionsUtils
1334 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1335 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301336 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001337 synchronized (mRestrictionsLock) {
1338 UserRestrictionsUtils.writeRestrictions(serializer,
1339 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1340 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001341 int[] userIdsToWrite;
1342 synchronized (mUsersLock) {
1343 userIdsToWrite = new int[mUsers.size()];
1344 for (int i = 0; i < userIdsToWrite.length; i++) {
1345 UserInfo user = mUsers.valueAt(i);
1346 userIdsToWrite[i] = user.id;
1347 }
1348 }
1349 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001350 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001351 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001352 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001353 }
1354
1355 serializer.endTag(null, TAG_USERS);
1356
1357 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001358 userListFile.finishWrite(fos);
1359 } catch (Exception e) {
1360 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001361 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001362 }
1363 }
1364
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001365 private UserInfo readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001366 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001367 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001368 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001369 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001370 long creationTime = 0L;
1371 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001372 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001373 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001374 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001375 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001376 Bundle baseRestrictions = new Bundle();
1377 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001378
1379 FileInputStream fis = null;
1380 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001381 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001382 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001383 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001384 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001385 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001386 int type;
1387 while ((type = parser.next()) != XmlPullParser.START_TAG
1388 && type != XmlPullParser.END_DOCUMENT) {
1389 ;
1390 }
1391
1392 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001393 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001394 return null;
1395 }
1396
1397 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001398 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1399 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001400 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001401 return null;
1402 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001403 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1404 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001405 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001406 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1407 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001408 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1409 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001410 restrictedProfileParentId = readIntAttribute(parser,
1411 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001412 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1413 if ("true".equals(valueString)) {
1414 partial = true;
1415 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001416 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1417 if ("true".equals(valueString)) {
1418 guestToRemove = true;
1419 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001420
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001421 int outerDepth = parser.getDepth();
1422 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1423 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1424 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1425 continue;
1426 }
1427 String tag = parser.getName();
1428 if (TAG_NAME.equals(tag)) {
1429 type = parser.next();
1430 if (type == XmlPullParser.TEXT) {
1431 name = parser.getText();
1432 }
1433 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001434 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1435 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1436 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001437 }
1438 }
1439 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001440
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001441 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001442 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001443 userInfo.creationTime = creationTime;
1444 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001445 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001446 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001447 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001448 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001449 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001450 mBaseUserRestrictions.put(id, baseRestrictions);
1451 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001452 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001453 return userInfo;
1454
1455 } catch (IOException ioe) {
1456 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001457 } finally {
1458 if (fis != null) {
1459 try {
1460 fis.close();
1461 } catch (IOException e) {
1462 }
1463 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001464 }
1465 return null;
1466 }
1467
Amith Yamasani920ace02012-09-20 22:15:37 -07001468 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1469 String valueString = parser.getAttributeValue(null, attr);
1470 if (valueString == null) return defaultValue;
1471 try {
1472 return Integer.parseInt(valueString);
1473 } catch (NumberFormatException nfe) {
1474 return defaultValue;
1475 }
1476 }
1477
1478 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1479 String valueString = parser.getAttributeValue(null, attr);
1480 if (valueString == null) return defaultValue;
1481 try {
1482 return Long.parseLong(valueString);
1483 } catch (NumberFormatException nfe) {
1484 return defaultValue;
1485 }
1486 }
1487
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001488 private boolean isPackageInstalled(String pkg, int userId) {
1489 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1490 PackageManager.GET_UNINSTALLED_PACKAGES,
1491 userId);
1492 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1493 return false;
1494 }
1495 return true;
1496 }
1497
Amith Yamasanib82add22013-07-09 11:24:44 -07001498 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001499 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001500 * Does not do any permissions checking.
1501 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001502 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001503 synchronized (mPackagesLock) {
1504 File dir = Environment.getUserSystemDirectory(userId);
1505 String[] files = dir.list();
1506 if (files == null) return;
1507 for (String fileName : files) {
1508 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1509 File resFile = new File(dir, fileName);
1510 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001511 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001512 }
1513 }
1514 }
1515 }
1516 }
1517
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001518 /**
1519 * Removes the app restrictions file for a specific package and user id, if it exists.
1520 */
1521 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1522 synchronized (mPackagesLock) {
1523 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001524 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001525 if (resFile.exists()) {
1526 resFile.delete();
1527 }
1528 }
1529 }
1530
Kenny Guya52dc3e2014-02-11 15:33:14 +00001531 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001532 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001533 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001534 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001535 }
1536
Amith Yamasani258848d2012-08-10 17:06:33 -07001537 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001538 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001539 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001540 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001541 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001542
Jessica Hummelbe81c802014-04-22 15:49:22 +01001543 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001544 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001545 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1546 return null;
1547 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001548 if (ActivityManager.isLowRamDeviceStatic()) {
1549 return null;
1550 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001551 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001552 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001553 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001554 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001555 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001556 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001557 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001558 synchronized (mPackagesLock) {
1559 UserInfo parent = null;
1560 if (parentId != UserHandle.USER_NULL) {
1561 synchronized (mUsersLock) {
1562 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001563 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001564 if (parent == null) return null;
1565 }
1566 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1567 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1568 return null;
1569 }
1570 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1571 // If we're not adding a guest user or a managed profile and the limit has
1572 // been reached, cannot add a user.
1573 return null;
1574 }
1575 // If we're adding a guest and there already exists one, bail.
1576 if (isGuest && findCurrentGuestUser() != null) {
1577 return null;
1578 }
1579 // In legacy mode, restricted profile's parent can only be the owner user
1580 if (isRestricted && !UserManager.isSplitSystemUser()
1581 && (parentId != UserHandle.USER_SYSTEM)) {
1582 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1583 return null;
1584 }
1585 if (isRestricted && UserManager.isSplitSystemUser()) {
1586 if (parent == null) {
1587 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1588 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001589 return null;
1590 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001591 if (!parent.canHaveProfile()) {
1592 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1593 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001594 return null;
1595 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001596 }
1597 // In split system user mode, we assign the first human user the primary flag.
1598 // And if there is no device owner, we also assign the admin flag to primary user.
1599 if (UserManager.isSplitSystemUser()
1600 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1601 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001602 synchronized (mUsersLock) {
1603 if (!mIsDeviceManaged) {
1604 flags |= UserInfo.FLAG_ADMIN;
1605 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001606 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001607 }
1608 userId = getNextAvailableId();
1609 userInfo = new UserInfo(userId, name, null, flags);
1610 userInfo.serialNumber = mNextSerialNumber++;
1611 long now = System.currentTimeMillis();
1612 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1613 userInfo.partial = true;
1614 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1615 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001616 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001617 }
1618 writeUserListLP();
1619 if (parent != null) {
1620 if (isManagedProfile) {
1621 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1622 parent.profileGroupId = parent.id;
1623 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001624 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001625 userInfo.profileGroupId = parent.profileGroupId;
1626 } else if (isRestricted) {
1627 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1628 parent.restrictedProfileParentId = parent.id;
1629 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001630 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001631 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001632 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001633 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001634 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001635 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1636 storage.createUserKey(userId, userInfo.serialNumber);
1637 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1638 final String volumeUuid = vol.getFsUuid();
1639 try {
1640 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1641 storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
1642 enforceSerialNumber(userDir, userInfo.serialNumber);
1643 } catch (IOException e) {
1644 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1645 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001646 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001647 mPm.createNewUser(userId);
1648 userInfo.partial = false;
1649 synchronized (mPackagesLock) {
1650 writeUserLP(userInfo);
1651 }
1652 updateUserIds();
1653 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001654 if (isGuest) {
1655 synchronized (mGuestRestrictions) {
1656 restrictions.putAll(mGuestRestrictions);
1657 }
1658 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001659 synchronized (mRestrictionsLock) {
1660 mBaseUserRestrictions.append(userId, restrictions);
1661 }
1662 mPm.newUserCreated(userId);
1663 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1664 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1665 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1666 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001667 } finally {
1668 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001669 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001670 return userInfo;
1671 }
1672
Amith Yamasani0b285492011-04-14 17:35:23 -07001673 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001674 * @hide
1675 */
1676 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1677 checkManageUsersPermission("setupRestrictedProfile");
1678 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1679 if (user == null) {
1680 return null;
1681 }
1682 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1683 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1684 // the putIntForUser() will fail.
1685 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1686 android.provider.Settings.Secure.LOCATION_MODE,
1687 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1688 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1689 return user;
1690 }
1691
1692 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001693 * Find the current guest user. If the Guest user is partial,
1694 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001695 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001696 private UserInfo findCurrentGuestUser() {
1697 synchronized (mUsersLock) {
1698 final int size = mUsers.size();
1699 for (int i = 0; i < size; i++) {
1700 final UserInfo user = mUsers.valueAt(i);
1701 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1702 return user;
1703 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001704 }
1705 }
1706 return null;
1707 }
1708
1709 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001710 * Mark this guest user for deletion to allow us to create another guest
1711 * and switch to that user before actually removing this guest.
1712 * @param userHandle the userid of the current guest
1713 * @return whether the user could be marked for deletion
1714 */
1715 public boolean markGuestForDeletion(int userHandle) {
1716 checkManageUsersPermission("Only the system can remove users");
1717 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1718 UserManager.DISALLOW_REMOVE_USER, false)) {
1719 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1720 return false;
1721 }
1722
1723 long ident = Binder.clearCallingIdentity();
1724 try {
1725 final UserInfo user;
1726 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001727 synchronized (mUsersLock) {
1728 user = mUsers.get(userHandle);
1729 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1730 return false;
1731 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001732 }
1733 if (!user.isGuest()) {
1734 return false;
1735 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001736 // We set this to a guest user that is to be removed. This is a temporary state
1737 // where we are allowed to add new Guest users, even if this one is still not
1738 // removed. This user will still show up in getUserInfo() calls.
1739 // If we don't get around to removing this Guest user, it will be purged on next
1740 // startup.
1741 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001742 // Mark it as disabled, so that it isn't returned any more when
1743 // profiles are queried.
1744 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001745 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001746 }
1747 } finally {
1748 Binder.restoreCallingIdentity(ident);
1749 }
1750 return true;
1751 }
1752
1753 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001754 * Removes a user and all data directories created for that user. This method should be called
1755 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001756 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001757 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001758 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001759 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001760 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1761 UserManager.DISALLOW_REMOVE_USER, false)) {
1762 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1763 return false;
1764 }
1765
Kenny Guyee58b4f2014-05-23 15:19:53 +01001766 long ident = Binder.clearCallingIdentity();
1767 try {
1768 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001769 int currentUser = ActivityManager.getCurrentUser();
1770 if (currentUser == userHandle) {
1771 Log.w(LOG_TAG, "Current user cannot be removed");
1772 return false;
1773 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001774 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001775 synchronized (mUsersLock) {
1776 user = mUsers.get(userHandle);
1777 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1778 return false;
1779 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001780
Fyodor Kupolov82402752015-10-28 14:54:51 -07001781 // We remember deleted user IDs to prevent them from being
1782 // reused during the current boot; they can still be reused
1783 // after a reboot.
1784 mRemovingUserIds.put(userHandle, true);
1785 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001786
Kenny Guyee58b4f2014-05-23 15:19:53 +01001787 try {
1788 mAppOpsService.removeUser(userHandle);
1789 } catch (RemoteException e) {
1790 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1791 }
1792 // Set this to a partially created user, so that the user will be purged
1793 // on next startup, in case the runtime stops now before stopping and
1794 // removing the user completely.
1795 user.partial = true;
1796 // Mark it as disabled, so that it isn't returned any more when
1797 // profiles are queried.
1798 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001799 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001800 }
1801
1802 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1803 && user.isManagedProfile()) {
1804 // Send broadcast to notify system that the user removed was a
1805 // managed user.
1806 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1807 }
1808
1809 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1810 int res;
1811 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001812 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
1813 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001814 @Override
1815 public void userStopped(int userId) {
1816 finishRemoveUser(userId);
1817 }
1818 @Override
1819 public void userStopAborted(int userId) {
1820 }
1821 });
1822 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001823 return false;
1824 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001825 return res == ActivityManager.USER_OP_SUCCESS;
1826 } finally {
1827 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001828 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001829 }
1830
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001831 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001832 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001833 // Let other services shutdown any activity and clean up their state before completely
1834 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001835 long ident = Binder.clearCallingIdentity();
1836 try {
1837 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1838 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001839 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1840 android.Manifest.permission.MANAGE_USERS,
1841
1842 new BroadcastReceiver() {
1843 @Override
1844 public void onReceive(Context context, Intent intent) {
1845 if (DBG) {
1846 Slog.i(LOG_TAG,
1847 "USER_REMOVED broadcast sent, cleaning up user data "
1848 + userHandle);
1849 }
1850 new Thread() {
1851 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001852 // Clean up any ActivityManager state
1853 LocalServices.getService(ActivityManagerInternal.class)
1854 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001855 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001856 }
1857 }.start();
1858 }
1859 },
1860
1861 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001862 } finally {
1863 Binder.restoreCallingIdentity(ident);
1864 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001865 }
1866
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001867 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001868 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001869 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001870 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001871
1872 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001873 synchronized (mUsersLock) {
1874 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08001875 mIsUserManaged.delete(userHandle);
1876 }
1877 synchronized (mRestrictionsLock) {
1878 mBaseUserRestrictions.remove(userHandle);
1879 mAppliedUserRestrictions.remove(userHandle);
1880 mCachedEffectiveUserRestrictions.remove(userHandle);
1881 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001882 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001883 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001884 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001885 userFile.delete();
1886 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001887 synchronized (mPackagesLock) {
1888 writeUserListLP();
1889 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001890 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001891 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1892 }
1893
Amith Yamasani61f57372012-08-31 12:12:28 -07001894 private void removeDirectoryRecursive(File parent) {
1895 if (parent.isDirectory()) {
1896 String[] files = parent.list();
1897 for (String filename : files) {
1898 File child = new File(parent, filename);
1899 removeDirectoryRecursive(child);
1900 }
1901 }
1902 parent.delete();
1903 }
1904
Kenny Guyf8d3a232014-05-15 16:09:52 +01001905 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001906 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001907 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1908 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001909 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1910 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001911 }
1912
Amith Yamasani2a003292012-08-14 18:25:45 -07001913 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001914 public Bundle getApplicationRestrictions(String packageName) {
1915 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1916 }
1917
1918 @Override
1919 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001920 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001921 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001922 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001923 }
1924 synchronized (mPackagesLock) {
1925 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001926 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001927 }
1928 }
1929
1930 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001931 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001932 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001933 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001934 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001935 if (restrictions == null || restrictions.isEmpty()) {
1936 cleanAppRestrictionsForPackage(packageName, userId);
1937 } else {
1938 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001939 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001940 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001941 }
Robin Lee66e5d962014-04-09 16:44:21 +01001942
Kenny Guyd21b2182014-07-17 16:38:55 +01001943 if (isPackageInstalled(packageName, userId)) {
1944 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1945 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1946 changeIntent.setPackage(packageName);
1947 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1948 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1949 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001950 }
1951
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001952 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001953 mHandler.post(new Runnable() {
1954 @Override
1955 public void run() {
1956 List<ApplicationInfo> apps =
1957 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1958 userHandle).getList();
1959 final long ident = Binder.clearCallingIdentity();
1960 try {
1961 for (ApplicationInfo appInfo : apps) {
1962 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001963 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1964 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001965 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001966 userHandle);
1967 }
1968 }
1969 } finally {
1970 Binder.restoreCallingIdentity(ident);
1971 }
1972 }
1973 });
1974 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001975 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001976 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001977 try {
1978 return mContext.getPackageManager().getApplicationInfo(packageName,
1979 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1980 } catch (NameNotFoundException nnfe) {
1981 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001982 } finally {
1983 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001984 }
1985 }
1986
Fyodor Kupolov82402752015-10-28 14:54:51 -07001987 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001988 AtomicFile restrictionsFile =
1989 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1990 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001991 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001992 }
1993
1994 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001995 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001996 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001997 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001998 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001999 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002000 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002001
2002 FileInputStream fis = null;
2003 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002004 fis = restrictionsFile.openRead();
2005 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002006 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002007 XmlUtils.nextElement(parser);
2008 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002009 Slog.e(LOG_TAG, "Unable to read restrictions file "
2010 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002011 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002012 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002013 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2014 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002015 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002016 } catch (IOException|XmlPullParserException e) {
2017 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002018 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002019 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002020 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002021 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002022 }
2023
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002024 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2025 XmlPullParser parser) throws XmlPullParserException, IOException {
2026 int type = parser.getEventType();
2027 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2028 String key = parser.getAttributeValue(null, ATTR_KEY);
2029 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2030 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2031 if (multiple != null) {
2032 values.clear();
2033 int count = Integer.parseInt(multiple);
2034 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2035 if (type == XmlPullParser.START_TAG
2036 && parser.getName().equals(TAG_VALUE)) {
2037 values.add(parser.nextText().trim());
2038 count--;
2039 }
2040 }
2041 String [] valueStrings = new String[values.size()];
2042 values.toArray(valueStrings);
2043 restrictions.putStringArray(key, valueStrings);
2044 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2045 restrictions.putBundle(key, readBundleEntry(parser, values));
2046 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2047 final int outerDepth = parser.getDepth();
2048 ArrayList<Bundle> bundleList = new ArrayList<>();
2049 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2050 Bundle childBundle = readBundleEntry(parser, values);
2051 bundleList.add(childBundle);
2052 }
2053 restrictions.putParcelableArray(key,
2054 bundleList.toArray(new Bundle[bundleList.size()]));
2055 } else {
2056 String value = parser.nextText().trim();
2057 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2058 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2059 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2060 restrictions.putInt(key, Integer.parseInt(value));
2061 } else {
2062 restrictions.putString(key, value);
2063 }
2064 }
2065 }
2066 }
2067
2068 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2069 throws IOException, XmlPullParserException {
2070 Bundle childBundle = new Bundle();
2071 final int outerDepth = parser.getDepth();
2072 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2073 readEntry(childBundle, values, parser);
2074 }
2075 return childBundle;
2076 }
2077
Fyodor Kupolov82402752015-10-28 14:54:51 -07002078 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002079 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002080 AtomicFile restrictionsFile = new AtomicFile(
2081 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002082 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002083 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002084 }
2085
2086 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002087 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002088 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002089 try {
2090 fos = restrictionsFile.startWrite();
2091 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2092
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002093 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002094 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002095 serializer.startDocument(null, true);
2096 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2097
2098 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002099 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002100 serializer.endTag(null, TAG_RESTRICTIONS);
2101
2102 serializer.endDocument();
2103 restrictionsFile.finishWrite(fos);
2104 } catch (Exception e) {
2105 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002106 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2107 }
2108 }
2109
2110 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2111 throws IOException {
2112 for (String key : restrictions.keySet()) {
2113 Object value = restrictions.get(key);
2114 serializer.startTag(null, TAG_ENTRY);
2115 serializer.attribute(null, ATTR_KEY, key);
2116
2117 if (value instanceof Boolean) {
2118 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2119 serializer.text(value.toString());
2120 } else if (value instanceof Integer) {
2121 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2122 serializer.text(value.toString());
2123 } else if (value == null || value instanceof String) {
2124 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2125 serializer.text(value != null ? (String) value : "");
2126 } else if (value instanceof Bundle) {
2127 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2128 writeBundle((Bundle) value, serializer);
2129 } else if (value instanceof Parcelable[]) {
2130 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2131 Parcelable[] array = (Parcelable[]) value;
2132 for (Parcelable parcelable : array) {
2133 if (!(parcelable instanceof Bundle)) {
2134 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2135 }
2136 serializer.startTag(null, TAG_ENTRY);
2137 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2138 writeBundle((Bundle) parcelable, serializer);
2139 serializer.endTag(null, TAG_ENTRY);
2140 }
2141 } else {
2142 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2143 String[] values = (String[]) value;
2144 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2145 for (String choice : values) {
2146 serializer.startTag(null, TAG_VALUE);
2147 serializer.text(choice != null ? choice : "");
2148 serializer.endTag(null, TAG_VALUE);
2149 }
2150 }
2151 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002152 }
2153 }
2154
2155 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002156 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002157 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002158 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002159 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002160 }
2161 }
2162
2163 @Override
2164 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002165 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002166 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002167 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002168 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002169 }
2170 // Not found
2171 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002172 }
2173 }
2174
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002175 @Override
2176 public long getUserCreationTime(int userHandle) {
2177 int callingUserId = UserHandle.getCallingUserId();
2178 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002179 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002180 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002181 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002182 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002183 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002184 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002185 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002186 }
2187 }
2188 }
2189 if (userInfo == null) {
2190 throw new SecurityException("userHandle can only be the calling user or a managed "
2191 + "profile associated with this user");
2192 }
2193 return userInfo.creationTime;
2194 }
2195
Amith Yamasani0b285492011-04-14 17:35:23 -07002196 /**
2197 * Caches the list of user ids in an array, adjusting the array size when necessary.
2198 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002199 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002200 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002201 synchronized (mUsersLock) {
2202 final int userSize = mUsers.size();
2203 for (int i = 0; i < userSize; i++) {
2204 if (!mUsers.valueAt(i).partial) {
2205 num++;
2206 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002207 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002208 final int[] newUsers = new int[num];
2209 int n = 0;
2210 for (int i = 0; i < userSize; i++) {
2211 if (!mUsers.valueAt(i).partial) {
2212 newUsers[n++] = mUsers.keyAt(i);
2213 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002214 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002215 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002216 }
2217 }
2218
2219 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002220 * Called right before a user starts. This will not be called for the system user.
2221 */
2222 public void onBeforeStartUser(int userId) {
2223 synchronized (mRestrictionsLock) {
2224 applyUserRestrictionsLR(userId);
2225 }
2226 }
2227
2228 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002229 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002230 * @param userId the user that was just foregrounded
2231 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002232 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002233 UserInfo user = getUserInfoNoChecks(userId);
2234 if (user == null || user.partial) {
2235 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2236 return;
2237 }
2238 long now = System.currentTimeMillis();
2239 if (now > EPOCH_PLUS_30_YEARS) {
2240 user.lastLoggedInTime = now;
2241 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002242 }
2243 }
2244
2245 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002246 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002247 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2248 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002249 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002250 private int getNextAvailableId() {
2251 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002252 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002253 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002254 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002255 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002256 }
2257 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002258 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002259 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002260 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002261 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002262
Amith Yamasanifc95e702013-09-26 13:20:17 -07002263 private String packageToRestrictionsFileName(String packageName) {
2264 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2265 }
2266
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002267 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002268 * Enforce that serial number stored in user directory inode matches the
2269 * given expected value. Gracefully sets the serial number if currently
2270 * undefined.
2271 *
2272 * @throws IOException when problem extracting serial number, or serial
2273 * number is mismatched.
2274 */
2275 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2276 final int foundSerial = getSerialNumber(file);
2277 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2278
2279 if (foundSerial == -1) {
2280 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2281 try {
2282 setSerialNumber(file, serialNumber);
2283 } catch (IOException e) {
2284 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2285 }
2286
2287 } else if (foundSerial != serialNumber) {
2288 throw new IOException("Found serial number " + foundSerial
2289 + " doesn't match expected " + serialNumber);
2290 }
2291 }
2292
2293 /**
2294 * Set serial number stored in user directory inode.
2295 *
2296 * @throws IOException if serial number was already set
2297 */
2298 private static void setSerialNumber(File file, int serialNumber)
2299 throws IOException {
2300 try {
2301 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2302 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2303 } catch (ErrnoException e) {
2304 throw e.rethrowAsIOException();
2305 }
2306 }
2307
2308 /**
2309 * Return serial number stored in user directory inode.
2310 *
2311 * @return parsed serial number, or -1 if not set
2312 */
2313 private static int getSerialNumber(File file) throws IOException {
2314 try {
2315 final byte[] buf = new byte[256];
2316 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2317 final String serial = new String(buf, 0, len);
2318 try {
2319 return Integer.parseInt(serial);
2320 } catch (NumberFormatException e) {
2321 throw new IOException("Bad serial number: " + serial);
2322 }
2323 } catch (ErrnoException e) {
2324 if (e.errno == OsConstants.ENODATA) {
2325 return -1;
2326 } else {
2327 throw e.rethrowAsIOException();
2328 }
2329 }
2330 }
2331
Amith Yamasani920ace02012-09-20 22:15:37 -07002332 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002333 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2334 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2335 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2336 }
2337
2338 int onShellCommand(Shell shell, String cmd) {
2339 if (cmd == null) {
2340 return shell.handleDefaultCommands(cmd);
2341 }
2342
2343 final PrintWriter pw = shell.getOutPrintWriter();
2344 try {
2345 switch(cmd) {
2346 case "list":
2347 return runList(pw);
2348 }
2349 } catch (RemoteException e) {
2350 pw.println("Remote exception: " + e);
2351 }
2352 return -1;
2353 }
2354
2355 private int runList(PrintWriter pw) throws RemoteException {
2356 final IActivityManager am = ActivityManagerNative.getDefault();
2357 final List<UserInfo> users = getUsers(false);
2358 if (users == null) {
2359 pw.println("Error: couldn't get users");
2360 return 1;
2361 } else {
2362 pw.println("Users:");
2363 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002364 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002365 pw.println("\t" + users.get(i).toString() + running);
2366 }
2367 return 0;
2368 }
2369 }
2370
2371 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002372 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2373 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2374 != PackageManager.PERMISSION_GRANTED) {
2375 pw.println("Permission Denial: can't dump UserManager from from pid="
2376 + Binder.getCallingPid()
2377 + ", uid=" + Binder.getCallingUid()
2378 + " without permission "
2379 + android.Manifest.permission.DUMP);
2380 return;
2381 }
2382
2383 long now = System.currentTimeMillis();
2384 StringBuilder sb = new StringBuilder();
2385 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002386 synchronized (mUsersLock) {
2387 pw.println("Users:");
2388 for (int i = 0; i < mUsers.size(); i++) {
2389 UserInfo user = mUsers.valueAt(i);
2390 if (user == null) {
2391 continue;
2392 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002393 final int userId = user.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002394 pw.print(" "); pw.print(user);
2395 pw.print(" serialNo="); pw.print(user.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002396 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002397 pw.print(" <removing> ");
2398 }
2399 if (user.partial) {
2400 pw.print(" <partial>");
2401 }
2402 pw.println();
2403 pw.print(" Created: ");
2404 if (user.creationTime == 0) {
2405 pw.println("<unknown>");
2406 } else {
2407 sb.setLength(0);
2408 TimeUtils.formatDuration(now - user.creationTime, sb);
2409 sb.append(" ago");
2410 pw.println(sb);
2411 }
2412 pw.print(" Last logged in: ");
2413 if (user.lastLoggedInTime == 0) {
2414 pw.println("<unknown>");
2415 } else {
2416 sb.setLength(0);
2417 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2418 sb.append(" ago");
2419 pw.println(sb);
2420 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002421 pw.print(" Has profile owner: ");
2422 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002423 pw.println(" Restrictions:");
2424 synchronized (mRestrictionsLock) {
2425 UserRestrictionsUtils.dumpRestrictions(
2426 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002427 pw.println(" Device policy local restrictions:");
2428 UserRestrictionsUtils.dumpRestrictions(
2429 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002430 pw.println(" Effective restrictions:");
2431 UserRestrictionsUtils.dumpRestrictions(
2432 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2433 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002434 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002435 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002436 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002437 pw.println(" Device policy global restrictions:");
2438 synchronized (mRestrictionsLock) {
2439 UserRestrictionsUtils
2440 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2441 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002442 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002443 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002444 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002445 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002446 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002447 synchronized (mUsersLock) {
2448 pw.println();
2449 pw.println(" Device managed: " + mIsDeviceManaged);
2450 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002451 }
2452 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002453
2454 final class MainHandler extends Handler {
2455
2456 @Override
2457 public void handleMessage(Message msg) {
2458 switch (msg.what) {
2459 case WRITE_USER_MSG:
2460 removeMessages(WRITE_USER_MSG, msg.obj);
2461 synchronized (mPackagesLock) {
2462 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002463 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002464 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002465 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002466 }
2467 }
2468 }
2469 }
2470 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002471
2472 /**
2473 * @param userId
2474 * @return whether the user has been initialized yet
2475 */
2476 boolean isInitialized(int userId) {
2477 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2478 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002479
2480 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002481 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002482 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2483 @Nullable Bundle globalRestrictions) {
2484 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2485 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002486 }
2487
2488 @Override
2489 public Bundle getBaseUserRestrictions(int userId) {
2490 synchronized (mRestrictionsLock) {
2491 return mBaseUserRestrictions.get(userId);
2492 }
2493 }
2494
2495 @Override
2496 public void setBaseUserRestrictionsByDpmsForMigration(
2497 int userId, Bundle baseRestrictions) {
2498 synchronized (mRestrictionsLock) {
2499 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002500 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002501 }
2502
Fyodor Kupolov82402752015-10-28 14:54:51 -07002503 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002504 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002505 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002506 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002507 } else {
2508 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2509 }
2510 }
2511 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002512
2513 @Override
2514 public boolean getUserRestriction(int userId, String key) {
2515 return getUserRestrictions(userId).getBoolean(key);
2516 }
2517
2518 @Override
2519 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2520 synchronized (mUserRestrictionsListeners) {
2521 mUserRestrictionsListeners.add(listener);
2522 }
2523 }
2524
2525 @Override
2526 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2527 synchronized (mUserRestrictionsListeners) {
2528 mUserRestrictionsListeners.remove(listener);
2529 }
2530 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002531
2532 @Override
2533 public void setDeviceManaged(boolean isManaged) {
2534 synchronized (mUsersLock) {
2535 mIsDeviceManaged = isManaged;
2536 }
2537 }
2538
2539 @Override
2540 public void setUserManaged(int userId, boolean isManaged) {
2541 synchronized (mUsersLock) {
2542 mIsUserManaged.put(userId, isManaged);
2543 }
2544 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002545 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002546
2547 private class Shell extends ShellCommand {
2548 @Override
2549 public int onCommand(String cmd) {
2550 return onShellCommand(this, cmd);
2551 }
2552
2553 @Override
2554 public void onHelp() {
2555 final PrintWriter pw = getOutPrintWriter();
2556 pw.println("User manager (user) commands:");
2557 pw.println(" help");
2558 pw.println(" Print this help text.");
2559 pw.println("");
2560 pw.println(" list");
2561 pw.println(" Prints all users on the system.");
2562 }
2563 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002564
2565 private static void debug(String message) {
2566 Log.d(LOG_TAG, message +
2567 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2568 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002569}