blob: ff829ff321d5b4129d146cf6cb79d64179ee9a32 [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;
Xiaohui Chen203243a2015-07-16 11:55:47 -070027import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070031import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070032import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080033import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070035import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080038import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070039import android.os.Environment;
40import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080041import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080043import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010044import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070045import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070047import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070048import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040049import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070050import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070051import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070052import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070053import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080054import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010055import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070056import android.os.storage.VolumeInfo;
57import android.system.ErrnoException;
58import android.system.Os;
59import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070060import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070061import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import android.util.Slog;
63import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080064import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070065import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import android.util.Xml;
67
Makoto Onuki068c54a2015-10-13 14:34:03 -070068import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070069import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040070import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080071import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070072import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070073import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070074import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080075
76import org.xmlpull.v1.XmlPullParser;
77import org.xmlpull.v1.XmlPullParserException;
78import org.xmlpull.v1.XmlSerializer;
79
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import java.io.BufferedOutputStream;
81import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070082import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070084import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import java.io.FileOutputStream;
86import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070087import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010088import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070089import java.util.ArrayList;
90import java.util.List;
91
Fyodor Kupolov262f9952015-03-23 18:55:11 -070092import libcore.io.IoUtils;
93
Makoto Onuki068c54a2015-10-13 14:34:03 -070094/**
95 * Service for {@link UserManager}.
96 *
97 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -070098 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -080099 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700100 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
101 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
102 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700103 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700104public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700105 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800106 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
107 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700108
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700111 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700113 private static final String ATTR_CREATION_TIME = "created";
114 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700115 private static final String ATTR_SERIAL_NO = "serialNumber";
116 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700117 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700118 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700119 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100120 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700121 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530122 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800125 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800126 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800127 private static final String TAG_ENTRY = "entry";
128 private static final String TAG_VALUE = "value";
129 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700130 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800131 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700133 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
134 private static final String ATTR_TYPE_STRING = "s";
135 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700136 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700137 private static final String ATTR_TYPE_BUNDLE = "B";
138 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700139
Amith Yamasani0b285492011-04-14 17:35:23 -0700140 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700142 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100143 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800145 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700146 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800147
Amith Yamasani634cf312012-10-04 17:34:21 -0700148 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700149 // We need to keep process uid within Integer.MAX_VALUE.
150 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700151
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700152 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700153
Amith Yamasani920ace02012-09-20 22:15:37 -0700154 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
155
Nicolas Prevotb8186812015-08-06 15:00:03 +0100156 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700157 // without first making sure that the rest of the framework is prepared for it.
158 private static final int MAX_MANAGED_PROFILES = 1;
159
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800160 static final int WRITE_USER_MSG = 1;
161 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530162
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700163 private static final String XATTR_SERIAL = "user.serial";
164
Dianne Hackborn4428e172012-08-24 17:43:05 -0700165 private final Context mContext;
166 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700167 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700168 // Short-term lock for internal state, when interaction/sync with PM is not required
169 private final Object mUsersLock = new Object();
170 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800172 private final Handler mHandler;
173
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700174 private final File mUsersDir;
175 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700176
Fyodor Kupolov82402752015-10-28 14:54:51 -0700177 @GuardedBy("mUsersLock")
178 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700179
180 /**
181 * User restrictions set via UserManager. This doesn't include restrictions set by
182 * device owner / profile owners.
183 *
184 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
185 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
186 * maybe shared between {@link #mBaseUserRestrictions} and
187 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
188 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700189 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700190 */
191 @GuardedBy("mRestrictionsLock")
192 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
193
194 /**
195 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
196 * with device / profile owner restrictions. We'll initialize it lazily; use
197 * {@link #getEffectiveUserRestrictions} to access it.
198 *
199 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
200 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
201 * maybe shared between {@link #mBaseUserRestrictions} and
202 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
203 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700204 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700205 */
206 @GuardedBy("mRestrictionsLock")
207 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
208
Makoto Onuki4f160732015-10-27 17:15:38 -0700209 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800210 * User restrictions that have already been applied in
211 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
212 * that have changed since the last
213 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700214 */
215 @GuardedBy("mRestrictionsLock")
216 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
217
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800218 /**
219 * User restrictions set by {@link DevicePolicyManager} that should be applied to all users,
220 * including guests.
221 */
222 @GuardedBy("mRestrictionsLock")
223 private Bundle mDevicePolicyGlobalUserRestrictions;
224
225 /**
226 * User restrictions set by {@link DevicePolicyManager} for each user.
227 */
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 Onukid45a4a22015-11-02 17:17:38 -0800251 @GuardedBy("mUserRestrictionsListeners")
252 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
253 new ArrayList<>();
254
Amith Yamasani258848d2012-08-10 17:06:33 -0700255 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700256
Dianne Hackborn4428e172012-08-24 17:43:05 -0700257 public static UserManagerService getInstance() {
258 synchronized (UserManagerService.class) {
259 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700260 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700261 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700262
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800263 @VisibleForTesting
264 UserManagerService(File dataDir) {
265 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700266 }
267
Dianne Hackborn4428e172012-08-24 17:43:05 -0700268 /**
269 * Called by package manager to create the service. This is closely
270 * associated with the package manager, and the given lock is the
271 * package manager's own lock.
272 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800273 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
274 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700275 }
276
Dianne Hackborn4428e172012-08-24 17:43:05 -0700277 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800278 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700279 mContext = context;
280 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700281 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800282 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800283 synchronized (mPackagesLock) {
284 mUsersDir = new File(dataDir, USER_INFO_DIR);
285 mUsersDir.mkdirs();
286 // Make zeroth user directory, for services to migrate their files to that location
287 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
288 userZeroDir.mkdirs();
289 FileUtils.setPermissions(mUsersDir.toString(),
290 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
291 -1, -1);
292 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
293 initDefaultGuestRestrictions();
294 readUserListLP();
295 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700296 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700297 mLocalService = new LocalService();
298 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700299 }
300
301 void systemReady() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800302 // Prune out any partially created/partially removed users.
303 ArrayList<UserInfo> partials = new ArrayList<>();
304 synchronized (mUsersLock) {
305 final int userSize = mUsers.size();
306 for (int i = 0; i < userSize; i++) {
307 UserInfo ui = mUsers.valueAt(i);
308 if ((ui.partial || ui.guestToRemove) && i != 0) {
309 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700310 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700311 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700312 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800313 final int partialsSize = partials.size();
314 for (int i = 0; i < partialsSize; i++) {
315 UserInfo ui = partials.get(i);
316 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
317 + " (name=" + ui.name + ")");
318 removeUserState(ui.id);
319 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800320
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700321 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800322
Jason Monk62062992014-05-06 09:55:28 -0400323 mAppOpsService = IAppOpsService.Stub.asInterface(
324 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800325
326 synchronized (mRestrictionsLock) {
327 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400328 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700329 }
330
331 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700332 public UserInfo getPrimaryUser() {
333 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700334 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700335 final int userSize = mUsers.size();
336 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700337 UserInfo ui = mUsers.valueAt(i);
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800338 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700339 return ui;
340 }
341 }
342 }
343 return null;
344 }
345
346 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700347 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700348 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700349 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700350 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700351 final int userSize = mUsers.size();
352 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700353 UserInfo ui = mUsers.valueAt(i);
354 if (ui.partial) {
355 continue;
356 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800357 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700358 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700359 }
Amith Yamasani13593602012-03-22 16:16:17 -0700360 }
361 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700362 }
Amith Yamasani13593602012-03-22 16:16:17 -0700363 }
364
Amith Yamasani258848d2012-08-10 17:06:33 -0700365 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100366 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800367 if (userId != UserHandle.getCallingUserId()) {
368 checkManageUsersPermission("getting profiles related to user " + userId);
369 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700370 final long ident = Binder.clearCallingIdentity();
371 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700372 synchronized (mUsersLock) {
373 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100374 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700375 } finally {
376 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000377 }
378 }
379
Amith Yamasanibe465322014-04-24 13:45:17 -0700380 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700381 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
382 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700383 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700384 if (user == null) {
385 // Probably a dying user
386 return users;
387 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700388 final int userSize = mUsers.size();
389 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700390 UserInfo profile = mUsers.valueAt(i);
391 if (!isProfileOf(user, profile)) {
392 continue;
393 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100394 if (enabledOnly && !profile.isEnabled()) {
395 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700396 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700397 if (mRemovingUserIds.get(profile.id)) {
398 continue;
399 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700400 users.add(profile);
401 }
402 return users;
403 }
404
Jessica Hummelbe81c802014-04-22 15:49:22 +0100405 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700406 public int getCredentialOwnerProfile(int userHandle) {
407 checkManageUsersPermission("get the credential owner");
Jeff Sharkeyba512352015-11-12 20:17:45 -0800408 if (!StorageManager.isFileBasedEncryptionEnabled()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700409 synchronized (mUsersLock) {
410 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700411 if (profileParent != null) {
412 return profileParent.id;
413 }
414 }
415 }
416
417 return userHandle;
418 }
419
420 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700421 public boolean isSameProfileGroup(int userId, int otherUserId) {
422 if (userId == otherUserId) return true;
423 checkManageUsersPermission("check if in the same profile group");
424 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700425 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700426 }
427 }
428
Fyodor Kupolov82402752015-10-28 14:54:51 -0700429 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
430 synchronized (mUsersLock) {
431 UserInfo userInfo = getUserInfoLU(userId);
432 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
433 return false;
434 }
435 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
436 if (otherUserInfo == null
437 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
438 return false;
439 }
440 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700441 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700442 }
443
444 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100445 public UserInfo getProfileParent(int userHandle) {
446 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700447 synchronized (mUsersLock) {
448 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700449 }
450 }
451
Fyodor Kupolov82402752015-10-28 14:54:51 -0700452 private UserInfo getProfileParentLU(int userHandle) {
453 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700454 if (profile == null) {
455 return null;
456 }
457 int parentUserId = profile.profileGroupId;
458 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
459 return null;
460 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700461 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100462 }
463 }
464
Fyodor Kupolov82402752015-10-28 14:54:51 -0700465 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100466 return user.id == profile.id ||
467 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
468 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000469 }
470
471 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100472 public void setUserEnabled(int userId) {
473 checkManageUsersPermission("enable user");
474 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700475 UserInfo info;
476 synchronized (mUsersLock) {
477 info = getUserInfoLU(userId);
478 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100479 if (info != null && !info.isEnabled()) {
480 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700481 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100482 }
483 }
484 }
485
486 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700487 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700488 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700489 synchronized (mUsersLock) {
490 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700491 }
492 }
493
Amith Yamasani71e6c692013-03-24 17:39:28 -0700494 @Override
495 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700496 synchronized (mUsersLock) {
497 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700498 }
499 }
500
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700501 @Override
502 public boolean canHaveRestrictedProfile(int userId) {
503 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700504 synchronized (mUsersLock) {
505 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700506 if (userInfo == null || !userInfo.canHaveProfile()) {
507 return false;
508 }
509 if (!userInfo.isAdmin()) {
510 return false;
511 }
512 }
513 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
514 Context.DEVICE_POLICY_SERVICE);
515 // restricted profile can be created if there is no DO set and the admin user has no PO
Makoto Onukic8a5a552015-11-19 14:29:12 -0800516 return !dpm.isDeviceManaged() && dpm.getProfileOwnerAsUser(userId) == null;
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700517 }
518
Amith Yamasani195263742012-08-21 15:40:12 -0700519 /*
520 * Should be locked on mUsers before calling this.
521 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700522 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700523 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700524 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800525 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700526 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
527 return null;
528 }
529 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700530 }
531
Fyodor Kupolov82402752015-10-28 14:54:51 -0700532 /**
533 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
534 * <p>No permissions checking or any addition checks are made</p>
535 */
536 private UserInfo getUserInfoNoChecks(int userId) {
537 synchronized (mUsersLock) {
538 return mUsers.get(userId);
539 }
540 }
541
Amith Yamasani236b2b52015-08-18 14:32:14 -0700542 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700543 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700544 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700545 }
546
Amith Yamasani258848d2012-08-10 17:06:33 -0700547 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700548 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700549 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700550 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700551 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700552 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700553 if (info == null || info.partial) {
554 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
555 return;
556 }
Amith Yamasani13593602012-03-22 16:16:17 -0700557 if (name != null && !name.equals(info.name)) {
558 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700559 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700560 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700561 }
562 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700563 if (changed) {
564 sendUserInfoChangedBroadcast(userId);
565 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700566 }
567
Amith Yamasani258848d2012-08-10 17:06:33 -0700568 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700569 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700570 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400571 long ident = Binder.clearCallingIdentity();
572 try {
573 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700574 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400575 if (info == null || info.partial) {
576 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
577 return;
578 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700579 writeBitmapLP(info, bitmap);
580 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700581 }
Jason Monk9a944532014-07-08 09:31:21 -0400582 sendUserInfoChangedBroadcast(userId);
583 } finally {
584 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700585 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700586 }
587
588 private void sendUserInfoChangedBroadcast(int userId) {
589 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
590 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
591 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700592 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700593 }
594
Amith Yamasani258848d2012-08-10 17:06:33 -0700595 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100596 public ParcelFileDescriptor getUserIcon(int userId) {
597 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700598 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700599 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700600 if (info == null || info.partial) {
601 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
602 return null;
603 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700604 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100605 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
606 || callingGroupId != info.profileGroupId) {
607 checkManageUsersPermission("get the icon of a user who is not related");
608 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700609 if (info.iconPath == null) {
610 return null;
611 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100612 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700613 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100614
615 try {
616 return ParcelFileDescriptor.open(
617 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
618 } catch (FileNotFoundException e) {
619 Log.e(LOG_TAG, "Couldn't find icon file", e);
620 }
621 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700622 }
623
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700624 public void makeInitialized(int userId) {
625 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800626 boolean scheduleWriteUser = false;
627 UserInfo info;
628 synchronized (mUsersLock) {
629 info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700630 if (info == null || info.partial) {
631 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800632 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700633 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800634 if ((info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700635 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800636 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700637 }
638 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800639 if (scheduleWriteUser) {
640 scheduleWriteUser(info);
641 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700642 }
643
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700644 /**
645 * If default guest restrictions haven't been initialized yet, add the basic
646 * restrictions.
647 */
648 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800649 synchronized (mGuestRestrictions) {
650 if (mGuestRestrictions.isEmpty()) {
651 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
652 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
653 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700654 }
655 }
656
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800657 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530658 public Bundle getDefaultGuestRestrictions() {
659 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800660 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530661 return new Bundle(mGuestRestrictions);
662 }
663 }
664
665 @Override
666 public void setDefaultGuestRestrictions(Bundle restrictions) {
667 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800668 synchronized (mGuestRestrictions) {
669 mGuestRestrictions.clear();
670 mGuestRestrictions.putAll(restrictions);
671 }
672 synchronized (mPackagesLock) {
673 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530674 }
675 }
676
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800677 /**
678 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
679 */
680 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
681 @Nullable Bundle global) {
682 Preconditions.checkNotNull(local);
683 boolean globalChanged = false;
684 boolean localChanged;
685 synchronized (mRestrictionsLock) {
686 if (global != null) {
687 // Update global.
688 globalChanged = !UserRestrictionsUtils.areEqual(
689 mDevicePolicyGlobalUserRestrictions, global);
690 if (globalChanged) {
691 mDevicePolicyGlobalUserRestrictions = global;
692 }
693 }
694 {
695 // Update local.
696 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
697 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
698 if (localChanged) {
699 mDevicePolicyLocalUserRestrictions.put(userId, local);
700 }
701 }
702 }
703 if (DBG) {
704 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
705 + " global=" + global + (globalChanged ? " (changed)" : "")
706 + " local=" + local + (localChanged ? " (changed)" : "")
707 );
708 }
709 // Don't call them within the mRestrictionsLock.
710 synchronized (mPackagesLock) {
711 if (globalChanged) {
712 writeUserListLP();
713 }
714 if (localChanged) {
715 writeUserLP(getUserInfoNoChecks(userId));
716 }
717 }
718
719 synchronized (mRestrictionsLock) {
720 if (globalChanged) {
721 applyUserRestrictionsForAllUsersLR();
722 } else if (localChanged) {
723 applyUserRestrictionsLR(userId);
724 }
725 }
726 }
727
Makoto Onuki068c54a2015-10-13 14:34:03 -0700728 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700729 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800730 final Bundle baseRestrictions =
731 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
732 final Bundle global = mDevicePolicyGlobalUserRestrictions;
733 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700734
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800735 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
736 // Common case first.
737 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700738 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800739 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
740 UserRestrictionsUtils.merge(effective, global);
741 UserRestrictionsUtils.merge(effective, local);
742
Makoto Onuki068c54a2015-10-13 14:34:03 -0700743 return effective;
744 }
745
746 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700747 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700748 if (DBG) {
749 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
750 }
751 mCachedEffectiveUserRestrictions.remove(userId);
752 }
753
754 private Bundle getEffectiveUserRestrictions(int userId) {
755 synchronized (mRestrictionsLock) {
756 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
757 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700758 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700759 mCachedEffectiveUserRestrictions.put(userId, restrictions);
760 }
761 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700762 }
763 }
764
Makoto Onuki068c54a2015-10-13 14:34:03 -0700765 /** @return a specific user restriction that's in effect currently. */
766 @Override
767 public boolean hasUserRestriction(String restrictionKey, int userId) {
768 Bundle restrictions = getEffectiveUserRestrictions(userId);
769 return restrictions != null && restrictions.getBoolean(restrictionKey);
770 }
771
772 /**
773 * @return UserRestrictions that are in effect currently. This always returns a new
774 * {@link Bundle}.
775 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700776 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800777 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800778 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800779 }
780
781 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700782 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700783 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700784 synchronized (mRestrictionsLock) {
785 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
786 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800787 final Bundle newRestrictions = UserRestrictionsUtils.clone(
788 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700789 newRestrictions.putBoolean(key, value);
790
Fyodor Kupolov82402752015-10-28 14:54:51 -0700791 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700792 }
793 }
794
Makoto Onuki068c54a2015-10-13 14:34:03 -0700795 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800796 * Optionally updating user restrictions, calculate the effective user restrictions and also
797 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700798 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800799 * @param newRestrictions User restrictions to set.
800 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700801 * @param userId target user ID.
802 */
803 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700804 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700805 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800806
807 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
808 mAppliedUserRestrictions.get(userId));
809
810 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700811 if (newRestrictions != null) {
812 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800813 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
814
815 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700816 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
817 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800818
819 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
820 mBaseUserRestrictions.put(userId, newRestrictions);
821 scheduleWriteUser(getUserInfoNoChecks(userId));
822 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700823 }
824
Fyodor Kupolov82402752015-10-28 14:54:51 -0700825 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700826
Makoto Onuki759a7632015-10-28 16:43:10 -0700827 mCachedEffectiveUserRestrictions.put(userId, effective);
828
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800829 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700830 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800831 debug("Applying user restrictions: userId=" + userId
832 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700833 }
834
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800835 if (mAppOpsService != null) { // We skip it until system-ready.
836 final long token = Binder.clearCallingIdentity();
837 try {
838 mAppOpsService.setUserRestrictions(effective, userId);
839 } catch (RemoteException e) {
840 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
841 } finally {
842 Binder.restoreCallingIdentity(token);
843 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700844 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700845
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800846 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700847
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800848 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700849 }
850
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800851 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800852 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800853 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
854 // actually, but we still need some kind of synchronization otherwise we might end up
855 // calling listeners out-of-order, thus "LR".
856
857 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
858 return;
859 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800860
861 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
862 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
863
864 mHandler.post(new Runnable() {
865 @Override
866 public void run() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800867 synchronized (mRestrictionsLock) {
868 UserRestrictionsUtils.applyUserRestrictionsLR(
869 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
870 }
871
Makoto Onukid45a4a22015-11-02 17:17:38 -0800872 final UserRestrictionsListener[] listeners;
873 synchronized (mUserRestrictionsListeners) {
874 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
875 mUserRestrictionsListeners.toArray(listeners);
876 }
877 for (int i = 0; i < listeners.length; i++) {
878 listeners[i].onUserRestrictionsChanged(userId,
879 newRestrictionsFinal, prevRestrictionsFinal);
880 }
881 }
882 });
883 }
884
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800885 // Package private for the inner class.
886 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700887 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700888 }
889
890 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800891 // Package private for the inner class.
892 void applyUserRestrictionsForAllUsersLR() {
893 if (DBG) {
894 debug("applyUserRestrictionsForAllUsersLR");
895 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700896 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700897 mCachedEffectiveUserRestrictions.clear();
898
Makoto Onuki068c54a2015-10-13 14:34:03 -0700899 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
900 // it on a handler.
901 final Runnable r = new Runnable() {
902 @Override
903 public void run() {
904 // Then get the list of running users.
905 final int[] runningUsers;
906 try {
907 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
908 } catch (RemoteException e) {
909 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
910 return;
911 }
912 // Then re-calculate the effective restrictions and apply, only for running users.
913 // It's okay if a new user has started after the getRunningUserIds() call,
914 // because we'll do the same thing (re-calculate the restrictions and apply)
915 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700916 synchronized (mRestrictionsLock) {
917 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800918 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700919 }
920 }
921 }
922 };
923 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700924 }
925
Amith Yamasani258848d2012-08-10 17:06:33 -0700926 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700927 * Check if we've hit the limit of how many users can be created.
928 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700929 private boolean isUserLimitReached() {
930 int count;
931 synchronized (mUsersLock) {
932 count = getAliveUsersExcludingGuestsCountLU();
933 }
934 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700935 }
936
937 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000938 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700939 checkManageUsersPermission("check if more managed profiles can be added.");
940 if (ActivityManager.isLowRamDeviceStatic()) {
941 return false;
942 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700943 if (!mContext.getPackageManager().hasSystemFeature(
944 PackageManager.FEATURE_MANAGED_USERS)) {
945 return false;
946 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100947 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000948 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
949 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
950 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100951 return false;
952 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700953 synchronized(mUsersLock) {
954 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100955 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700956 return false;
957 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000958 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
959 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -0700960 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000961 return usersCountAfterRemoving == 1
962 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700963 }
964 }
965
Fyodor Kupolov82402752015-10-28 14:54:51 -0700966 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700967 int aliveUserCount = 0;
968 final int totalUserCount = mUsers.size();
969 // Skip over users being removed
970 for (int i = 0; i < totalUserCount; i++) {
971 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700972 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700973 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700974 aliveUserCount++;
975 }
976 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700977 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700978 }
979
980 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700981 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700982 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700983 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700984 *
985 * @param message used as message if SecurityException is thrown
986 * @throws SecurityException if the caller is not system or root
987 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700988 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700989 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700990 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400991 && ActivityManager.checkComponentPermission(
992 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700993 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
994 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
995 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400996 }
997
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700998 private static void checkSystemOrRoot(String message) {
999 final int uid = Binder.getCallingUid();
1000 if (uid != Process.SYSTEM_UID && uid != 0) {
1001 throw new SecurityException("Only system may call: " + message);
1002 }
1003 }
1004
Fyodor Kupolov82402752015-10-28 14:54:51 -07001005 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001006 try {
1007 File dir = new File(mUsersDir, Integer.toString(info.id));
1008 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001009 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001010 if (!dir.exists()) {
1011 dir.mkdir();
1012 FileUtils.setPermissions(
1013 dir.getPath(),
1014 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1015 -1, -1);
1016 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001017 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001018 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1019 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001020 info.iconPath = file.getAbsolutePath();
1021 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001022 try {
1023 os.close();
1024 } catch (IOException ioe) {
1025 // What the ... !
1026 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001027 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001028 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001029 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001030 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001031 }
1032
Amith Yamasani0b285492011-04-14 17:35:23 -07001033 /**
1034 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1035 * cache it elsewhere.
1036 * @return the array of user ids.
1037 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001038 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001039 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001040 return mUserIds;
1041 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001042 }
1043
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001044 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001045 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001046 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001047 return;
1048 }
1049 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001050 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001051 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001052 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001053 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001054 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001055 int type;
1056 while ((type = parser.next()) != XmlPullParser.START_TAG
1057 && type != XmlPullParser.END_DOCUMENT) {
1058 ;
1059 }
1060
1061 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001062 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001063 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001064 return;
1065 }
1066
Amith Yamasani2a003292012-08-14 18:25:45 -07001067 mNextSerialNumber = -1;
1068 if (parser.getName().equals(TAG_USERS)) {
1069 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1070 if (lastSerialNumber != null) {
1071 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1072 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001073 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1074 if (versionNumber != null) {
1075 mUserVersion = Integer.parseInt(versionNumber);
1076 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001077 }
1078
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001079 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1080
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001081 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301082 if (type == XmlPullParser.START_TAG) {
1083 final String name = parser.getName();
1084 if (name.equals(TAG_USER)) {
1085 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001086 UserInfo user = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001087
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301088 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001089 synchronized (mUsersLock) {
1090 mUsers.put(user.id, user);
1091 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1092 mNextSerialNumber = user.id + 1;
1093 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301094 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001095 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301096 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001097 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1098 && type != XmlPullParser.END_TAG) {
1099 if (type == XmlPullParser.START_TAG) {
1100 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001101 synchronized (mGuestRestrictions) {
1102 UserRestrictionsUtils
1103 .readRestrictions(parser, mGuestRestrictions);
1104 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001105 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1106 ) {
1107 UserRestrictionsUtils.readRestrictions(parser,
1108 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001109 }
1110 break;
1111 }
1112 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001113 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001114 }
1115 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001116 synchronized (mRestrictionsLock) {
1117 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1118 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001119 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001120 upgradeIfNecessaryLP();
1121 } catch (IOException | XmlPullParserException e) {
1122 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001123 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001124 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001125 }
1126 }
1127
Amith Yamasani6f34b412012-10-22 18:19:27 -07001128 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001129 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001130 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001131 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001132 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001133 int userVersion = mUserVersion;
1134 if (userVersion < 1) {
1135 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001136 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001137 if ("Primary".equals(user.name)) {
1138 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001139 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001140 }
1141 userVersion = 1;
1142 }
1143
Amith Yamasanibc9625052012-11-15 14:39:18 -08001144 if (userVersion < 2) {
1145 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001146 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001147 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1148 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001149 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001150 }
1151 userVersion = 2;
1152 }
1153
Amith Yamasani350962c2013-08-06 11:18:53 -07001154
Amith Yamasani5e486f52013-08-07 11:06:44 -07001155 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001156 userVersion = 4;
1157 }
1158
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001159 if (userVersion < 5) {
1160 initDefaultGuestRestrictions();
1161 userVersion = 5;
1162 }
1163
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001164 if (userVersion < 6) {
1165 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001166 synchronized (mUsersLock) {
1167 for (int i = 0; i < mUsers.size(); i++) {
1168 UserInfo user = mUsers.valueAt(i);
1169 // In non-split mode, only user 0 can have restricted profiles
1170 if (!splitSystemUser && user.isRestricted()
1171 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1172 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001173 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001174 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001175 }
1176 }
1177 userVersion = 6;
1178 }
1179
Amith Yamasani6f34b412012-10-22 18:19:27 -07001180 if (userVersion < USER_VERSION) {
1181 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1182 + USER_VERSION);
1183 } else {
1184 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001185
1186 if (originalVersion < mUserVersion) {
1187 writeUserListLP();
1188 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001189 }
1190 }
1191
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001192 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001193 int flags = UserInfo.FLAG_INITIALIZED;
1194 // In split system user mode, the admin and primary flags are assigned to the first human
1195 // user.
1196 if (!UserManager.isSplitSystemUser()) {
1197 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1198 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001199 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001200 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001201 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001202 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001203 synchronized (mUsersLock) {
1204 mUsers.put(system.id, system);
1205 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001206 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001207 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001208
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001209 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001210 synchronized (mRestrictionsLock) {
1211 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1212 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001213
Fyodor Kupolov82402752015-10-28 14:54:51 -07001214 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001215 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001216
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001217 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001218 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001219 }
1220
Makoto Onuki9e935a32015-11-06 14:24:24 -08001221 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001222 if (DBG) {
1223 debug("scheduleWriteUser");
1224 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001225 // No need to wrap it within a lock -- worst case, we'll just post the same message
1226 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001227 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1228 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1229 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1230 }
1231 }
1232
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001233 /*
1234 * Writes the user file in this format:
1235 *
1236 * <user flags="20039023" id="0">
1237 * <name>Primary</name>
1238 * </user>
1239 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001240 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001241 if (DBG) {
1242 debug("writeUserLP " + userInfo);
1243 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001244 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001245 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001246 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001247 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001248 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1249
1250 // XmlSerializer serializer = XmlUtils.serializerInstance();
1251 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001252 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001253 serializer.startDocument(null, true);
1254 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1255
1256 serializer.startTag(null, TAG_USER);
1257 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001258 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001259 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001260 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1261 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1262 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001263 if (userInfo.iconPath != null) {
1264 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1265 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001266 if (userInfo.partial) {
1267 serializer.attribute(null, ATTR_PARTIAL, "true");
1268 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001269 if (userInfo.guestToRemove) {
1270 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1271 }
Kenny Guy2a764942014-04-02 13:29:20 +01001272 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1273 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1274 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001275 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001276 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1277 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1278 Integer.toString(userInfo.restrictedProfileParentId));
1279 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001280 serializer.startTag(null, TAG_NAME);
1281 serializer.text(userInfo.name);
1282 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001283 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001284 UserRestrictionsUtils.writeRestrictions(serializer,
1285 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1286 UserRestrictionsUtils.writeRestrictions(serializer,
1287 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1288 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001289 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001290 serializer.endTag(null, TAG_USER);
1291
1292 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001293 userFile.finishWrite(fos);
1294 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001295 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001296 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001297 }
1298 }
1299
1300 /*
1301 * Writes the user list file in this format:
1302 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001303 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001304 * <user id="0"></user>
1305 * <user id="2"></user>
1306 * </users>
1307 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001308 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001309 if (DBG) {
1310 debug("writeUserList");
1311 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001312 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001313 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001314 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001315 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001316 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1317
1318 // XmlSerializer serializer = XmlUtils.serializerInstance();
1319 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001320 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001321 serializer.startDocument(null, true);
1322 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1323
1324 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001325 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001326 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001327
Adam Lesinskieddeb492014-09-08 17:50:03 -07001328 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001329 synchronized (mGuestRestrictions) {
1330 UserRestrictionsUtils
1331 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1332 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301333 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001334 synchronized (mRestrictionsLock) {
1335 UserRestrictionsUtils.writeRestrictions(serializer,
1336 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1337 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001338 int[] userIdsToWrite;
1339 synchronized (mUsersLock) {
1340 userIdsToWrite = new int[mUsers.size()];
1341 for (int i = 0; i < userIdsToWrite.length; i++) {
1342 UserInfo user = mUsers.valueAt(i);
1343 userIdsToWrite[i] = user.id;
1344 }
1345 }
1346 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001347 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001348 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001349 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001350 }
1351
1352 serializer.endTag(null, TAG_USERS);
1353
1354 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001355 userListFile.finishWrite(fos);
1356 } catch (Exception e) {
1357 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001358 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001359 }
1360 }
1361
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001362 private UserInfo readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001363 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001364 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001365 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001366 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001367 long creationTime = 0L;
1368 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001369 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001370 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001371 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001372 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001373 Bundle baseRestrictions = new Bundle();
1374 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001375
1376 FileInputStream fis = null;
1377 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001378 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001379 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001380 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001381 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001382 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001383 int type;
1384 while ((type = parser.next()) != XmlPullParser.START_TAG
1385 && type != XmlPullParser.END_DOCUMENT) {
1386 ;
1387 }
1388
1389 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001390 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001391 return null;
1392 }
1393
1394 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001395 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1396 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001397 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001398 return null;
1399 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001400 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1401 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001402 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001403 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1404 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001405 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1406 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001407 restrictedProfileParentId = readIntAttribute(parser,
1408 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001409 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1410 if ("true".equals(valueString)) {
1411 partial = true;
1412 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001413 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1414 if ("true".equals(valueString)) {
1415 guestToRemove = true;
1416 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001417
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001418 int outerDepth = parser.getDepth();
1419 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1420 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1421 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1422 continue;
1423 }
1424 String tag = parser.getName();
1425 if (TAG_NAME.equals(tag)) {
1426 type = parser.next();
1427 if (type == XmlPullParser.TEXT) {
1428 name = parser.getText();
1429 }
1430 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001431 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1432 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1433 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001434 }
1435 }
1436 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001437
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001438 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001439 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001440 userInfo.creationTime = creationTime;
1441 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001442 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001443 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001444 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001445 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001446 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001447 mBaseUserRestrictions.put(id, baseRestrictions);
1448 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001449 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001450 return userInfo;
1451
1452 } catch (IOException ioe) {
1453 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001454 } finally {
1455 if (fis != null) {
1456 try {
1457 fis.close();
1458 } catch (IOException e) {
1459 }
1460 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001461 }
1462 return null;
1463 }
1464
Amith Yamasani920ace02012-09-20 22:15:37 -07001465 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1466 String valueString = parser.getAttributeValue(null, attr);
1467 if (valueString == null) return defaultValue;
1468 try {
1469 return Integer.parseInt(valueString);
1470 } catch (NumberFormatException nfe) {
1471 return defaultValue;
1472 }
1473 }
1474
1475 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1476 String valueString = parser.getAttributeValue(null, attr);
1477 if (valueString == null) return defaultValue;
1478 try {
1479 return Long.parseLong(valueString);
1480 } catch (NumberFormatException nfe) {
1481 return defaultValue;
1482 }
1483 }
1484
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001485 private boolean isPackageInstalled(String pkg, int userId) {
1486 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1487 PackageManager.GET_UNINSTALLED_PACKAGES,
1488 userId);
1489 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1490 return false;
1491 }
1492 return true;
1493 }
1494
Amith Yamasanib82add22013-07-09 11:24:44 -07001495 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001496 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001497 * Does not do any permissions checking.
1498 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001499 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001500 synchronized (mPackagesLock) {
1501 File dir = Environment.getUserSystemDirectory(userId);
1502 String[] files = dir.list();
1503 if (files == null) return;
1504 for (String fileName : files) {
1505 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1506 File resFile = new File(dir, fileName);
1507 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001508 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001509 }
1510 }
1511 }
1512 }
1513 }
1514
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001515 /**
1516 * Removes the app restrictions file for a specific package and user id, if it exists.
1517 */
1518 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1519 synchronized (mPackagesLock) {
1520 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001521 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001522 if (resFile.exists()) {
1523 resFile.delete();
1524 }
1525 }
1526 }
1527
Kenny Guya52dc3e2014-02-11 15:33:14 +00001528 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001529 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001530 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001531 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001532 }
1533
Amith Yamasani258848d2012-08-10 17:06:33 -07001534 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001535 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001536 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001537 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001538 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001539
Jessica Hummelbe81c802014-04-22 15:49:22 +01001540 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001541 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001542 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1543 return null;
1544 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001545 if (ActivityManager.isLowRamDeviceStatic()) {
1546 return null;
1547 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001548 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001549 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001550 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001551 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001552 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001553 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001554 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001555 synchronized (mPackagesLock) {
1556 UserInfo parent = null;
1557 if (parentId != UserHandle.USER_NULL) {
1558 synchronized (mUsersLock) {
1559 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001560 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001561 if (parent == null) return null;
1562 }
1563 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1564 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1565 return null;
1566 }
1567 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1568 // If we're not adding a guest user or a managed profile and the limit has
1569 // been reached, cannot add a user.
1570 return null;
1571 }
1572 // If we're adding a guest and there already exists one, bail.
1573 if (isGuest && findCurrentGuestUser() != null) {
1574 return null;
1575 }
1576 // In legacy mode, restricted profile's parent can only be the owner user
1577 if (isRestricted && !UserManager.isSplitSystemUser()
1578 && (parentId != UserHandle.USER_SYSTEM)) {
1579 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1580 return null;
1581 }
1582 if (isRestricted && UserManager.isSplitSystemUser()) {
1583 if (parent == null) {
1584 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1585 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001586 return null;
1587 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001588 if (!parent.canHaveProfile()) {
1589 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1590 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001591 return null;
1592 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001593 }
1594 // In split system user mode, we assign the first human user the primary flag.
1595 // And if there is no device owner, we also assign the admin flag to primary user.
1596 if (UserManager.isSplitSystemUser()
1597 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1598 flags |= UserInfo.FLAG_PRIMARY;
1599 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1600 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1601 if (devicePolicyManager == null
Makoto Onukic8a5a552015-11-19 14:29:12 -08001602 || !devicePolicyManager.isDeviceManaged()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001603 flags |= UserInfo.FLAG_ADMIN;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001604 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001605 }
1606 userId = getNextAvailableId();
1607 userInfo = new UserInfo(userId, name, null, flags);
1608 userInfo.serialNumber = mNextSerialNumber++;
1609 long now = System.currentTimeMillis();
1610 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1611 userInfo.partial = true;
1612 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1613 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001614 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001615 }
1616 writeUserListLP();
1617 if (parent != null) {
1618 if (isManagedProfile) {
1619 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1620 parent.profileGroupId = parent.id;
1621 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001622 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001623 userInfo.profileGroupId = parent.profileGroupId;
1624 } else if (isRestricted) {
1625 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1626 parent.restrictedProfileParentId = parent.id;
1627 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001628 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001629 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001630 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001631 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001632 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001633 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1634 storage.createUserKey(userId, userInfo.serialNumber);
1635 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1636 final String volumeUuid = vol.getFsUuid();
1637 try {
1638 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1639 storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
1640 enforceSerialNumber(userDir, userInfo.serialNumber);
1641 } catch (IOException e) {
1642 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1643 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001644 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001645 mPm.createNewUser(userId);
1646 userInfo.partial = false;
1647 synchronized (mPackagesLock) {
1648 writeUserLP(userInfo);
1649 }
1650 updateUserIds();
1651 Bundle restrictions = new Bundle();
1652 synchronized (mRestrictionsLock) {
1653 mBaseUserRestrictions.append(userId, restrictions);
1654 }
1655 mPm.newUserCreated(userId);
1656 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1657 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1658 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1659 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001660 } finally {
1661 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001662 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001663 return userInfo;
1664 }
1665
Amith Yamasani0b285492011-04-14 17:35:23 -07001666 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001667 * @hide
1668 */
1669 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1670 checkManageUsersPermission("setupRestrictedProfile");
1671 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1672 if (user == null) {
1673 return null;
1674 }
1675 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1676 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1677 // the putIntForUser() will fail.
1678 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1679 android.provider.Settings.Secure.LOCATION_MODE,
1680 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1681 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1682 return user;
1683 }
1684
1685 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001686 * Find the current guest user. If the Guest user is partial,
1687 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001688 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001689 private UserInfo findCurrentGuestUser() {
1690 synchronized (mUsersLock) {
1691 final int size = mUsers.size();
1692 for (int i = 0; i < size; i++) {
1693 final UserInfo user = mUsers.valueAt(i);
1694 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1695 return user;
1696 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001697 }
1698 }
1699 return null;
1700 }
1701
1702 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001703 * Mark this guest user for deletion to allow us to create another guest
1704 * and switch to that user before actually removing this guest.
1705 * @param userHandle the userid of the current guest
1706 * @return whether the user could be marked for deletion
1707 */
1708 public boolean markGuestForDeletion(int userHandle) {
1709 checkManageUsersPermission("Only the system can remove users");
1710 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1711 UserManager.DISALLOW_REMOVE_USER, false)) {
1712 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1713 return false;
1714 }
1715
1716 long ident = Binder.clearCallingIdentity();
1717 try {
1718 final UserInfo user;
1719 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001720 synchronized (mUsersLock) {
1721 user = mUsers.get(userHandle);
1722 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1723 return false;
1724 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001725 }
1726 if (!user.isGuest()) {
1727 return false;
1728 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001729 // We set this to a guest user that is to be removed. This is a temporary state
1730 // where we are allowed to add new Guest users, even if this one is still not
1731 // removed. This user will still show up in getUserInfo() calls.
1732 // If we don't get around to removing this Guest user, it will be purged on next
1733 // startup.
1734 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001735 // Mark it as disabled, so that it isn't returned any more when
1736 // profiles are queried.
1737 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001738 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001739 }
1740 } finally {
1741 Binder.restoreCallingIdentity(ident);
1742 }
1743 return true;
1744 }
1745
1746 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001747 * Removes a user and all data directories created for that user. This method should be called
1748 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001749 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001750 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001751 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001752 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001753 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1754 UserManager.DISALLOW_REMOVE_USER, false)) {
1755 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1756 return false;
1757 }
1758
Kenny Guyee58b4f2014-05-23 15:19:53 +01001759 long ident = Binder.clearCallingIdentity();
1760 try {
1761 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001762 int currentUser = ActivityManager.getCurrentUser();
1763 if (currentUser == userHandle) {
1764 Log.w(LOG_TAG, "Current user cannot be removed");
1765 return false;
1766 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001767 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001768 synchronized (mUsersLock) {
1769 user = mUsers.get(userHandle);
1770 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1771 return false;
1772 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001773
Fyodor Kupolov82402752015-10-28 14:54:51 -07001774 // We remember deleted user IDs to prevent them from being
1775 // reused during the current boot; they can still be reused
1776 // after a reboot.
1777 mRemovingUserIds.put(userHandle, true);
1778 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001779
Kenny Guyee58b4f2014-05-23 15:19:53 +01001780 try {
1781 mAppOpsService.removeUser(userHandle);
1782 } catch (RemoteException e) {
1783 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1784 }
1785 // Set this to a partially created user, so that the user will be purged
1786 // on next startup, in case the runtime stops now before stopping and
1787 // removing the user completely.
1788 user.partial = true;
1789 // Mark it as disabled, so that it isn't returned any more when
1790 // profiles are queried.
1791 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001792 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001793 }
1794
1795 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1796 && user.isManagedProfile()) {
1797 // Send broadcast to notify system that the user removed was a
1798 // managed user.
1799 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1800 }
1801
1802 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1803 int res;
1804 try {
1805 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1806 new IStopUserCallback.Stub() {
1807 @Override
1808 public void userStopped(int userId) {
1809 finishRemoveUser(userId);
1810 }
1811 @Override
1812 public void userStopAborted(int userId) {
1813 }
1814 });
1815 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001816 return false;
1817 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001818 return res == ActivityManager.USER_OP_SUCCESS;
1819 } finally {
1820 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001821 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001822 }
1823
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001824 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001825 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001826 // Let other services shutdown any activity and clean up their state before completely
1827 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001828 long ident = Binder.clearCallingIdentity();
1829 try {
1830 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1831 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001832 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1833 android.Manifest.permission.MANAGE_USERS,
1834
1835 new BroadcastReceiver() {
1836 @Override
1837 public void onReceive(Context context, Intent intent) {
1838 if (DBG) {
1839 Slog.i(LOG_TAG,
1840 "USER_REMOVED broadcast sent, cleaning up user data "
1841 + userHandle);
1842 }
1843 new Thread() {
1844 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001845 // Clean up any ActivityManager state
1846 LocalServices.getService(ActivityManagerInternal.class)
1847 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001848 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001849 }
1850 }.start();
1851 }
1852 },
1853
1854 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001855 } finally {
1856 Binder.restoreCallingIdentity(ident);
1857 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001858 }
1859
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001860 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001861 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001862 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001863 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001864
1865 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001866 synchronized (mUsersLock) {
1867 mUsers.remove(userHandle);
1868 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001869 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001870 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001871 userFile.delete();
1872 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001873 synchronized (mPackagesLock) {
1874 writeUserListLP();
1875 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001876 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001877 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1878 }
1879
Amith Yamasani61f57372012-08-31 12:12:28 -07001880 private void removeDirectoryRecursive(File parent) {
1881 if (parent.isDirectory()) {
1882 String[] files = parent.list();
1883 for (String filename : files) {
1884 File child = new File(parent, filename);
1885 removeDirectoryRecursive(child);
1886 }
1887 }
1888 parent.delete();
1889 }
1890
Kenny Guyf8d3a232014-05-15 16:09:52 +01001891 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001892 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001893 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1894 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001895 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1896 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001897 }
1898
Amith Yamasani2a003292012-08-14 18:25:45 -07001899 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001900 public Bundle getApplicationRestrictions(String packageName) {
1901 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1902 }
1903
1904 @Override
1905 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001906 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001907 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001908 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001909 }
1910 synchronized (mPackagesLock) {
1911 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001912 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001913 }
1914 }
1915
1916 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001917 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001918 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001919 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001920 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001921 if (restrictions == null || restrictions.isEmpty()) {
1922 cleanAppRestrictionsForPackage(packageName, userId);
1923 } else {
1924 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001925 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001926 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001927 }
Robin Lee66e5d962014-04-09 16:44:21 +01001928
Kenny Guyd21b2182014-07-17 16:38:55 +01001929 if (isPackageInstalled(packageName, userId)) {
1930 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1931 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1932 changeIntent.setPackage(packageName);
1933 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1934 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1935 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001936 }
1937
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001938 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001939 mHandler.post(new Runnable() {
1940 @Override
1941 public void run() {
1942 List<ApplicationInfo> apps =
1943 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1944 userHandle).getList();
1945 final long ident = Binder.clearCallingIdentity();
1946 try {
1947 for (ApplicationInfo appInfo : apps) {
1948 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001949 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1950 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001951 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001952 userHandle);
1953 }
1954 }
1955 } finally {
1956 Binder.restoreCallingIdentity(ident);
1957 }
1958 }
1959 });
1960 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001961 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001962 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001963 try {
1964 return mContext.getPackageManager().getApplicationInfo(packageName,
1965 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1966 } catch (NameNotFoundException nnfe) {
1967 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001968 } finally {
1969 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001970 }
1971 }
1972
Fyodor Kupolov82402752015-10-28 14:54:51 -07001973 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001974 AtomicFile restrictionsFile =
1975 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1976 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001977 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001978 }
1979
1980 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001981 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001982 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001983 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001984 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001985 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001986 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001987
1988 FileInputStream fis = null;
1989 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001990 fis = restrictionsFile.openRead();
1991 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001992 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001993 XmlUtils.nextElement(parser);
1994 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001995 Slog.e(LOG_TAG, "Unable to read restrictions file "
1996 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001997 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001998 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001999 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2000 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002001 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002002 } catch (IOException|XmlPullParserException e) {
2003 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002004 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002005 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002006 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002007 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002008 }
2009
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002010 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2011 XmlPullParser parser) throws XmlPullParserException, IOException {
2012 int type = parser.getEventType();
2013 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2014 String key = parser.getAttributeValue(null, ATTR_KEY);
2015 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2016 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2017 if (multiple != null) {
2018 values.clear();
2019 int count = Integer.parseInt(multiple);
2020 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2021 if (type == XmlPullParser.START_TAG
2022 && parser.getName().equals(TAG_VALUE)) {
2023 values.add(parser.nextText().trim());
2024 count--;
2025 }
2026 }
2027 String [] valueStrings = new String[values.size()];
2028 values.toArray(valueStrings);
2029 restrictions.putStringArray(key, valueStrings);
2030 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2031 restrictions.putBundle(key, readBundleEntry(parser, values));
2032 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2033 final int outerDepth = parser.getDepth();
2034 ArrayList<Bundle> bundleList = new ArrayList<>();
2035 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2036 Bundle childBundle = readBundleEntry(parser, values);
2037 bundleList.add(childBundle);
2038 }
2039 restrictions.putParcelableArray(key,
2040 bundleList.toArray(new Bundle[bundleList.size()]));
2041 } else {
2042 String value = parser.nextText().trim();
2043 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2044 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2045 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2046 restrictions.putInt(key, Integer.parseInt(value));
2047 } else {
2048 restrictions.putString(key, value);
2049 }
2050 }
2051 }
2052 }
2053
2054 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2055 throws IOException, XmlPullParserException {
2056 Bundle childBundle = new Bundle();
2057 final int outerDepth = parser.getDepth();
2058 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2059 readEntry(childBundle, values, parser);
2060 }
2061 return childBundle;
2062 }
2063
Fyodor Kupolov82402752015-10-28 14:54:51 -07002064 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002065 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002066 AtomicFile restrictionsFile = new AtomicFile(
2067 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002068 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002069 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002070 }
2071
2072 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002073 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002074 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002075 try {
2076 fos = restrictionsFile.startWrite();
2077 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2078
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002079 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002080 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002081 serializer.startDocument(null, true);
2082 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2083
2084 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002085 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002086 serializer.endTag(null, TAG_RESTRICTIONS);
2087
2088 serializer.endDocument();
2089 restrictionsFile.finishWrite(fos);
2090 } catch (Exception e) {
2091 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002092 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2093 }
2094 }
2095
2096 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2097 throws IOException {
2098 for (String key : restrictions.keySet()) {
2099 Object value = restrictions.get(key);
2100 serializer.startTag(null, TAG_ENTRY);
2101 serializer.attribute(null, ATTR_KEY, key);
2102
2103 if (value instanceof Boolean) {
2104 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2105 serializer.text(value.toString());
2106 } else if (value instanceof Integer) {
2107 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2108 serializer.text(value.toString());
2109 } else if (value == null || value instanceof String) {
2110 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2111 serializer.text(value != null ? (String) value : "");
2112 } else if (value instanceof Bundle) {
2113 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2114 writeBundle((Bundle) value, serializer);
2115 } else if (value instanceof Parcelable[]) {
2116 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2117 Parcelable[] array = (Parcelable[]) value;
2118 for (Parcelable parcelable : array) {
2119 if (!(parcelable instanceof Bundle)) {
2120 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2121 }
2122 serializer.startTag(null, TAG_ENTRY);
2123 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2124 writeBundle((Bundle) parcelable, serializer);
2125 serializer.endTag(null, TAG_ENTRY);
2126 }
2127 } else {
2128 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2129 String[] values = (String[]) value;
2130 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2131 for (String choice : values) {
2132 serializer.startTag(null, TAG_VALUE);
2133 serializer.text(choice != null ? choice : "");
2134 serializer.endTag(null, TAG_VALUE);
2135 }
2136 }
2137 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002138 }
2139 }
2140
2141 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002142 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002143 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002144 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002145 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002146 }
2147 }
2148
2149 @Override
2150 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002151 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002152 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002153 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002154 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002155 }
2156 // Not found
2157 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002158 }
2159 }
2160
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002161 @Override
2162 public long getUserCreationTime(int userHandle) {
2163 int callingUserId = UserHandle.getCallingUserId();
2164 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002165 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002166 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002167 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002168 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002169 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002170 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002171 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002172 }
2173 }
2174 }
2175 if (userInfo == null) {
2176 throw new SecurityException("userHandle can only be the calling user or a managed "
2177 + "profile associated with this user");
2178 }
2179 return userInfo.creationTime;
2180 }
2181
Amith Yamasani0b285492011-04-14 17:35:23 -07002182 /**
2183 * Caches the list of user ids in an array, adjusting the array size when necessary.
2184 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002185 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002186 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002187 synchronized (mUsersLock) {
2188 final int userSize = mUsers.size();
2189 for (int i = 0; i < userSize; i++) {
2190 if (!mUsers.valueAt(i).partial) {
2191 num++;
2192 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002193 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002194 final int[] newUsers = new int[num];
2195 int n = 0;
2196 for (int i = 0; i < userSize; i++) {
2197 if (!mUsers.valueAt(i).partial) {
2198 newUsers[n++] = mUsers.keyAt(i);
2199 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002200 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002201 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002202 }
2203 }
2204
2205 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002206 * Called right before a user starts. This will not be called for the system user.
2207 */
2208 public void onBeforeStartUser(int userId) {
2209 synchronized (mRestrictionsLock) {
2210 applyUserRestrictionsLR(userId);
2211 }
2212 }
2213
2214 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002215 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002216 * @param userId the user that was just foregrounded
2217 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002218 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002219 UserInfo user = getUserInfoNoChecks(userId);
2220 if (user == null || user.partial) {
2221 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2222 return;
2223 }
2224 long now = System.currentTimeMillis();
2225 if (now > EPOCH_PLUS_30_YEARS) {
2226 user.lastLoggedInTime = now;
2227 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002228 }
2229 }
2230
2231 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002232 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002233 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2234 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002235 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002236 private int getNextAvailableId() {
2237 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002238 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002239 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002240 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002241 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002242 }
2243 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002244 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002245 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002246 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002247 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002248
Amith Yamasanifc95e702013-09-26 13:20:17 -07002249 private String packageToRestrictionsFileName(String packageName) {
2250 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2251 }
2252
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002253 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002254 * Enforce that serial number stored in user directory inode matches the
2255 * given expected value. Gracefully sets the serial number if currently
2256 * undefined.
2257 *
2258 * @throws IOException when problem extracting serial number, or serial
2259 * number is mismatched.
2260 */
2261 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2262 final int foundSerial = getSerialNumber(file);
2263 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2264
2265 if (foundSerial == -1) {
2266 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2267 try {
2268 setSerialNumber(file, serialNumber);
2269 } catch (IOException e) {
2270 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2271 }
2272
2273 } else if (foundSerial != serialNumber) {
2274 throw new IOException("Found serial number " + foundSerial
2275 + " doesn't match expected " + serialNumber);
2276 }
2277 }
2278
2279 /**
2280 * Set serial number stored in user directory inode.
2281 *
2282 * @throws IOException if serial number was already set
2283 */
2284 private static void setSerialNumber(File file, int serialNumber)
2285 throws IOException {
2286 try {
2287 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2288 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2289 } catch (ErrnoException e) {
2290 throw e.rethrowAsIOException();
2291 }
2292 }
2293
2294 /**
2295 * Return serial number stored in user directory inode.
2296 *
2297 * @return parsed serial number, or -1 if not set
2298 */
2299 private static int getSerialNumber(File file) throws IOException {
2300 try {
2301 final byte[] buf = new byte[256];
2302 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2303 final String serial = new String(buf, 0, len);
2304 try {
2305 return Integer.parseInt(serial);
2306 } catch (NumberFormatException e) {
2307 throw new IOException("Bad serial number: " + serial);
2308 }
2309 } catch (ErrnoException e) {
2310 if (e.errno == OsConstants.ENODATA) {
2311 return -1;
2312 } else {
2313 throw e.rethrowAsIOException();
2314 }
2315 }
2316 }
2317
Amith Yamasani920ace02012-09-20 22:15:37 -07002318 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002319 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2320 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2321 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2322 }
2323
2324 int onShellCommand(Shell shell, String cmd) {
2325 if (cmd == null) {
2326 return shell.handleDefaultCommands(cmd);
2327 }
2328
2329 final PrintWriter pw = shell.getOutPrintWriter();
2330 try {
2331 switch(cmd) {
2332 case "list":
2333 return runList(pw);
2334 }
2335 } catch (RemoteException e) {
2336 pw.println("Remote exception: " + e);
2337 }
2338 return -1;
2339 }
2340
2341 private int runList(PrintWriter pw) throws RemoteException {
2342 final IActivityManager am = ActivityManagerNative.getDefault();
2343 final List<UserInfo> users = getUsers(false);
2344 if (users == null) {
2345 pw.println("Error: couldn't get users");
2346 return 1;
2347 } else {
2348 pw.println("Users:");
2349 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002350 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002351 pw.println("\t" + users.get(i).toString() + running);
2352 }
2353 return 0;
2354 }
2355 }
2356
2357 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002358 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2359 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2360 != PackageManager.PERMISSION_GRANTED) {
2361 pw.println("Permission Denial: can't dump UserManager from from pid="
2362 + Binder.getCallingPid()
2363 + ", uid=" + Binder.getCallingUid()
2364 + " without permission "
2365 + android.Manifest.permission.DUMP);
2366 return;
2367 }
2368
2369 long now = System.currentTimeMillis();
2370 StringBuilder sb = new StringBuilder();
2371 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002372 synchronized (mUsersLock) {
2373 pw.println("Users:");
2374 for (int i = 0; i < mUsers.size(); i++) {
2375 UserInfo user = mUsers.valueAt(i);
2376 if (user == null) {
2377 continue;
2378 }
2379 pw.print(" "); pw.print(user);
2380 pw.print(" serialNo="); pw.print(user.serialNumber);
2381 if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2382 pw.print(" <removing> ");
2383 }
2384 if (user.partial) {
2385 pw.print(" <partial>");
2386 }
2387 pw.println();
2388 pw.print(" Created: ");
2389 if (user.creationTime == 0) {
2390 pw.println("<unknown>");
2391 } else {
2392 sb.setLength(0);
2393 TimeUtils.formatDuration(now - user.creationTime, sb);
2394 sb.append(" ago");
2395 pw.println(sb);
2396 }
2397 pw.print(" Last logged in: ");
2398 if (user.lastLoggedInTime == 0) {
2399 pw.println("<unknown>");
2400 } else {
2401 sb.setLength(0);
2402 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2403 sb.append(" ago");
2404 pw.println(sb);
2405 }
2406 pw.println(" Restrictions:");
2407 synchronized (mRestrictionsLock) {
2408 UserRestrictionsUtils.dumpRestrictions(
2409 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002410 pw.println(" Device policy local restrictions:");
2411 UserRestrictionsUtils.dumpRestrictions(
2412 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002413 pw.println(" Effective restrictions:");
2414 UserRestrictionsUtils.dumpRestrictions(
2415 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2416 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002417 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002418 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002419 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002420 pw.println(" Device policy global restrictions:");
2421 synchronized (mRestrictionsLock) {
2422 UserRestrictionsUtils
2423 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2424 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002425 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002426 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002427 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002428 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002429 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002430 }
2431 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002432
2433 final class MainHandler extends Handler {
2434
2435 @Override
2436 public void handleMessage(Message msg) {
2437 switch (msg.what) {
2438 case WRITE_USER_MSG:
2439 removeMessages(WRITE_USER_MSG, msg.obj);
2440 synchronized (mPackagesLock) {
2441 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002442 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002443 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002444 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002445 }
2446 }
2447 }
2448 }
2449 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002450
2451 /**
2452 * @param userId
2453 * @return whether the user has been initialized yet
2454 */
2455 boolean isInitialized(int userId) {
2456 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2457 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002458
2459 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002460 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002461 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2462 @Nullable Bundle globalRestrictions) {
2463 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2464 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002465 }
2466
2467 @Override
2468 public Bundle getBaseUserRestrictions(int userId) {
2469 synchronized (mRestrictionsLock) {
2470 return mBaseUserRestrictions.get(userId);
2471 }
2472 }
2473
2474 @Override
2475 public void setBaseUserRestrictionsByDpmsForMigration(
2476 int userId, Bundle baseRestrictions) {
2477 synchronized (mRestrictionsLock) {
2478 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002479 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002480 }
2481
Fyodor Kupolov82402752015-10-28 14:54:51 -07002482 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002483 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002484 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002485 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002486 } else {
2487 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2488 }
2489 }
2490 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002491
2492 @Override
2493 public boolean getUserRestriction(int userId, String key) {
2494 return getUserRestrictions(userId).getBoolean(key);
2495 }
2496
2497 @Override
2498 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2499 synchronized (mUserRestrictionsListeners) {
2500 mUserRestrictionsListeners.add(listener);
2501 }
2502 }
2503
2504 @Override
2505 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2506 synchronized (mUserRestrictionsListeners) {
2507 mUserRestrictionsListeners.remove(listener);
2508 }
2509 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002510 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002511
2512 private class Shell extends ShellCommand {
2513 @Override
2514 public int onCommand(String cmd) {
2515 return onShellCommand(this, cmd);
2516 }
2517
2518 @Override
2519 public void onHelp() {
2520 final PrintWriter pw = getOutPrintWriter();
2521 pw.println("User manager (user) commands:");
2522 pw.println(" help");
2523 pw.println(" Print this help text.");
2524 pw.println("");
2525 pw.println(" list");
2526 pw.println(" Prints all users on the system.");
2527 }
2528 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002529
2530 private static void debug(String message) {
2531 Log.d(LOG_TAG, message +
2532 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2533 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002534}