blob: e44e63cfbb26c1297d440a245424f561253f78cf [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);
338 if (ui.isPrimary()) {
339 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");
Clara Bayarri965da392015-10-28 17:53:53 +0000408 if (!mContext.getSystemService(StorageManager.class).isPerUserEncryptionEnabled()) {
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
516 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
517 }
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 Onuki1a2cd742015-11-16 13:51:27 -0800784 if (!UserRestrictionsUtils.isSystemControlled(key)) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700785 setUserRestrictionNoCheck(key, value, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700786 }
787 }
788
789 @Override
790 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
791 checkSystemOrRoot("setSystemControlledUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700792 setUserRestrictionNoCheck(key, value, userId);
793 }
794
795 private void setUserRestrictionNoCheck(String key, boolean value, int userId) {
796 synchronized (mRestrictionsLock) {
797 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
798 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800799 final Bundle newRestrictions = UserRestrictionsUtils.clone(
800 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700801 newRestrictions.putBoolean(key, value);
802
Fyodor Kupolov82402752015-10-28 14:54:51 -0700803 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700804 }
805 }
806
Makoto Onuki068c54a2015-10-13 14:34:03 -0700807 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800808 * Optionally updating user restrictions, calculate the effective user restrictions and also
809 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700810 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800811 * @param newRestrictions User restrictions to set.
812 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700813 * @param userId target user ID.
814 */
815 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700816 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700817 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800818
819 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
820 mAppliedUserRestrictions.get(userId));
821
822 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700823 if (newRestrictions != null) {
824 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800825 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
826
827 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700828 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
829 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800830
831 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
832 mBaseUserRestrictions.put(userId, newRestrictions);
833 scheduleWriteUser(getUserInfoNoChecks(userId));
834 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700835 }
836
Fyodor Kupolov82402752015-10-28 14:54:51 -0700837 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700838
Makoto Onuki759a7632015-10-28 16:43:10 -0700839 mCachedEffectiveUserRestrictions.put(userId, effective);
840
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800841 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700842 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800843 debug("Applying user restrictions: userId=" + userId
844 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700845 }
846
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800847 if (mAppOpsService != null) { // We skip it until system-ready.
848 final long token = Binder.clearCallingIdentity();
849 try {
850 mAppOpsService.setUserRestrictions(effective, userId);
851 } catch (RemoteException e) {
852 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
853 } finally {
854 Binder.restoreCallingIdentity(token);
855 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700856 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700857
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800858 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700859
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800860 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700861 }
862
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800863 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800864 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800865 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
866 // actually, but we still need some kind of synchronization otherwise we might end up
867 // calling listeners out-of-order, thus "LR".
868
869 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
870 return;
871 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800872
873 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
874 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
875
876 mHandler.post(new Runnable() {
877 @Override
878 public void run() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800879 synchronized (mRestrictionsLock) {
880 UserRestrictionsUtils.applyUserRestrictionsLR(
881 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
882 }
883
Makoto Onukid45a4a22015-11-02 17:17:38 -0800884 final UserRestrictionsListener[] listeners;
885 synchronized (mUserRestrictionsListeners) {
886 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
887 mUserRestrictionsListeners.toArray(listeners);
888 }
889 for (int i = 0; i < listeners.length; i++) {
890 listeners[i].onUserRestrictionsChanged(userId,
891 newRestrictionsFinal, prevRestrictionsFinal);
892 }
893 }
894 });
895 }
896
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800897 // Package private for the inner class.
898 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700899 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700900 }
901
902 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800903 // Package private for the inner class.
904 void applyUserRestrictionsForAllUsersLR() {
905 if (DBG) {
906 debug("applyUserRestrictionsForAllUsersLR");
907 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700908 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700909 mCachedEffectiveUserRestrictions.clear();
910
Makoto Onuki068c54a2015-10-13 14:34:03 -0700911 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
912 // it on a handler.
913 final Runnable r = new Runnable() {
914 @Override
915 public void run() {
916 // Then get the list of running users.
917 final int[] runningUsers;
918 try {
919 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
920 } catch (RemoteException e) {
921 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
922 return;
923 }
924 // Then re-calculate the effective restrictions and apply, only for running users.
925 // It's okay if a new user has started after the getRunningUserIds() call,
926 // because we'll do the same thing (re-calculate the restrictions and apply)
927 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700928 synchronized (mRestrictionsLock) {
929 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800930 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700931 }
932 }
933 }
934 };
935 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700936 }
937
Amith Yamasani258848d2012-08-10 17:06:33 -0700938 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700939 * Check if we've hit the limit of how many users can be created.
940 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700941 private boolean isUserLimitReached() {
942 int count;
943 synchronized (mUsersLock) {
944 count = getAliveUsersExcludingGuestsCountLU();
945 }
946 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700947 }
948
949 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000950 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700951 checkManageUsersPermission("check if more managed profiles can be added.");
952 if (ActivityManager.isLowRamDeviceStatic()) {
953 return false;
954 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700955 if (!mContext.getPackageManager().hasSystemFeature(
956 PackageManager.FEATURE_MANAGED_USERS)) {
957 return false;
958 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100959 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000960 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
961 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
962 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100963 return false;
964 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700965 synchronized(mUsersLock) {
966 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100967 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700968 return false;
969 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000970 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
971 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -0700972 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000973 return usersCountAfterRemoving == 1
974 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700975 }
976 }
977
Fyodor Kupolov82402752015-10-28 14:54:51 -0700978 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700979 int aliveUserCount = 0;
980 final int totalUserCount = mUsers.size();
981 // Skip over users being removed
982 for (int i = 0; i < totalUserCount; i++) {
983 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700984 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700985 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700986 aliveUserCount++;
987 }
988 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700989 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700990 }
991
992 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700993 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700994 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700995 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700996 *
997 * @param message used as message if SecurityException is thrown
998 * @throws SecurityException if the caller is not system or root
999 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001000 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001001 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -07001002 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001003 && ActivityManager.checkComponentPermission(
1004 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001005 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1006 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1007 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001008 }
1009
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001010 private static void checkSystemOrRoot(String message) {
1011 final int uid = Binder.getCallingUid();
1012 if (uid != Process.SYSTEM_UID && uid != 0) {
1013 throw new SecurityException("Only system may call: " + message);
1014 }
1015 }
1016
Fyodor Kupolov82402752015-10-28 14:54:51 -07001017 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001018 try {
1019 File dir = new File(mUsersDir, Integer.toString(info.id));
1020 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001021 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001022 if (!dir.exists()) {
1023 dir.mkdir();
1024 FileUtils.setPermissions(
1025 dir.getPath(),
1026 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1027 -1, -1);
1028 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001029 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001030 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1031 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001032 info.iconPath = file.getAbsolutePath();
1033 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001034 try {
1035 os.close();
1036 } catch (IOException ioe) {
1037 // What the ... !
1038 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001039 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001040 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001041 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001042 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001043 }
1044
Amith Yamasani0b285492011-04-14 17:35:23 -07001045 /**
1046 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1047 * cache it elsewhere.
1048 * @return the array of user ids.
1049 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001050 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001051 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001052 return mUserIds;
1053 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001054 }
1055
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001056 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001057 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001058 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001059 return;
1060 }
1061 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001062 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001063 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001064 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001065 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001066 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001067 int type;
1068 while ((type = parser.next()) != XmlPullParser.START_TAG
1069 && type != XmlPullParser.END_DOCUMENT) {
1070 ;
1071 }
1072
1073 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001074 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001075 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001076 return;
1077 }
1078
Amith Yamasani2a003292012-08-14 18:25:45 -07001079 mNextSerialNumber = -1;
1080 if (parser.getName().equals(TAG_USERS)) {
1081 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1082 if (lastSerialNumber != null) {
1083 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1084 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001085 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1086 if (versionNumber != null) {
1087 mUserVersion = Integer.parseInt(versionNumber);
1088 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001089 }
1090
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001091 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1092
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001093 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301094 if (type == XmlPullParser.START_TAG) {
1095 final String name = parser.getName();
1096 if (name.equals(TAG_USER)) {
1097 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001098 UserInfo user = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001099
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301100 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001101 synchronized (mUsersLock) {
1102 mUsers.put(user.id, user);
1103 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1104 mNextSerialNumber = user.id + 1;
1105 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301106 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001107 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301108 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001109 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1110 && type != XmlPullParser.END_TAG) {
1111 if (type == XmlPullParser.START_TAG) {
1112 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001113 synchronized (mGuestRestrictions) {
1114 UserRestrictionsUtils
1115 .readRestrictions(parser, mGuestRestrictions);
1116 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001117 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1118 ) {
1119 UserRestrictionsUtils.readRestrictions(parser,
1120 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001121 }
1122 break;
1123 }
1124 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001125 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001126 }
1127 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001128 synchronized (mRestrictionsLock) {
1129 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1130 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001131 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001132 upgradeIfNecessaryLP();
1133 } catch (IOException | XmlPullParserException e) {
1134 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001135 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001136 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001137 }
1138 }
1139
Amith Yamasani6f34b412012-10-22 18:19:27 -07001140 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001141 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001142 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001143 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001144 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001145 int userVersion = mUserVersion;
1146 if (userVersion < 1) {
1147 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001148 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001149 if ("Primary".equals(user.name)) {
1150 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001151 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001152 }
1153 userVersion = 1;
1154 }
1155
Amith Yamasanibc9625052012-11-15 14:39:18 -08001156 if (userVersion < 2) {
1157 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001158 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001159 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1160 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001161 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001162 }
1163 userVersion = 2;
1164 }
1165
Amith Yamasani350962c2013-08-06 11:18:53 -07001166
Amith Yamasani5e486f52013-08-07 11:06:44 -07001167 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001168 userVersion = 4;
1169 }
1170
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001171 if (userVersion < 5) {
1172 initDefaultGuestRestrictions();
1173 userVersion = 5;
1174 }
1175
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001176 if (userVersion < 6) {
1177 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001178 synchronized (mUsersLock) {
1179 for (int i = 0; i < mUsers.size(); i++) {
1180 UserInfo user = mUsers.valueAt(i);
1181 // In non-split mode, only user 0 can have restricted profiles
1182 if (!splitSystemUser && user.isRestricted()
1183 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1184 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001185 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001186 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001187 }
1188 }
1189 userVersion = 6;
1190 }
1191
Amith Yamasani6f34b412012-10-22 18:19:27 -07001192 if (userVersion < USER_VERSION) {
1193 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1194 + USER_VERSION);
1195 } else {
1196 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001197
1198 if (originalVersion < mUserVersion) {
1199 writeUserListLP();
1200 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001201 }
1202 }
1203
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001204 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001205 int flags = UserInfo.FLAG_INITIALIZED;
1206 // In split system user mode, the admin and primary flags are assigned to the first human
1207 // user.
1208 if (!UserManager.isSplitSystemUser()) {
1209 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1210 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001211 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001212 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001213 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001214 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001215 synchronized (mUsersLock) {
1216 mUsers.put(system.id, system);
1217 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001218 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001219 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001220
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001221 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001222 synchronized (mRestrictionsLock) {
1223 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1224 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001225
Fyodor Kupolov82402752015-10-28 14:54:51 -07001226 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001227 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001228
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001229 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001230 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001231 }
1232
Makoto Onuki9e935a32015-11-06 14:24:24 -08001233 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001234 if (DBG) {
1235 debug("scheduleWriteUser");
1236 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001237 // No need to wrap it within a lock -- worst case, we'll just post the same message
1238 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001239 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1240 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1241 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1242 }
1243 }
1244
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001245 /*
1246 * Writes the user file in this format:
1247 *
1248 * <user flags="20039023" id="0">
1249 * <name>Primary</name>
1250 * </user>
1251 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001252 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001253 if (DBG) {
1254 debug("writeUserLP " + userInfo);
1255 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001256 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001257 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001258 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001259 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001260 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1261
1262 // XmlSerializer serializer = XmlUtils.serializerInstance();
1263 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001264 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001265 serializer.startDocument(null, true);
1266 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1267
1268 serializer.startTag(null, TAG_USER);
1269 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001270 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001271 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001272 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1273 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1274 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001275 if (userInfo.iconPath != null) {
1276 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1277 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001278 if (userInfo.partial) {
1279 serializer.attribute(null, ATTR_PARTIAL, "true");
1280 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001281 if (userInfo.guestToRemove) {
1282 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1283 }
Kenny Guy2a764942014-04-02 13:29:20 +01001284 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1285 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1286 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001287 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001288 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1289 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1290 Integer.toString(userInfo.restrictedProfileParentId));
1291 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001292 serializer.startTag(null, TAG_NAME);
1293 serializer.text(userInfo.name);
1294 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001295 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001296 UserRestrictionsUtils.writeRestrictions(serializer,
1297 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1298 UserRestrictionsUtils.writeRestrictions(serializer,
1299 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1300 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001301 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001302 serializer.endTag(null, TAG_USER);
1303
1304 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001305 userFile.finishWrite(fos);
1306 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001307 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001308 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001309 }
1310 }
1311
1312 /*
1313 * Writes the user list file in this format:
1314 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001315 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001316 * <user id="0"></user>
1317 * <user id="2"></user>
1318 * </users>
1319 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001320 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001321 if (DBG) {
1322 debug("writeUserList");
1323 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001324 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001325 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001326 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001327 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001328 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1329
1330 // XmlSerializer serializer = XmlUtils.serializerInstance();
1331 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001332 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001333 serializer.startDocument(null, true);
1334 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1335
1336 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001337 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001338 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001339
Adam Lesinskieddeb492014-09-08 17:50:03 -07001340 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001341 synchronized (mGuestRestrictions) {
1342 UserRestrictionsUtils
1343 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1344 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301345 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001346 synchronized (mRestrictionsLock) {
1347 UserRestrictionsUtils.writeRestrictions(serializer,
1348 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1349 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001350 int[] userIdsToWrite;
1351 synchronized (mUsersLock) {
1352 userIdsToWrite = new int[mUsers.size()];
1353 for (int i = 0; i < userIdsToWrite.length; i++) {
1354 UserInfo user = mUsers.valueAt(i);
1355 userIdsToWrite[i] = user.id;
1356 }
1357 }
1358 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001359 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001360 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001361 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001362 }
1363
1364 serializer.endTag(null, TAG_USERS);
1365
1366 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001367 userListFile.finishWrite(fos);
1368 } catch (Exception e) {
1369 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001370 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001371 }
1372 }
1373
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001374 private UserInfo readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001375 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001376 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001377 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001378 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001379 long creationTime = 0L;
1380 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001381 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001382 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001383 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001384 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001385 Bundle baseRestrictions = new Bundle();
1386 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001387
1388 FileInputStream fis = null;
1389 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001390 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001391 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001392 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001393 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001394 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001395 int type;
1396 while ((type = parser.next()) != XmlPullParser.START_TAG
1397 && type != XmlPullParser.END_DOCUMENT) {
1398 ;
1399 }
1400
1401 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001402 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001403 return null;
1404 }
1405
1406 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001407 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1408 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001409 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001410 return null;
1411 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001412 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1413 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001414 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001415 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1416 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001417 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1418 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001419 restrictedProfileParentId = readIntAttribute(parser,
1420 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001421 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1422 if ("true".equals(valueString)) {
1423 partial = true;
1424 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001425 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1426 if ("true".equals(valueString)) {
1427 guestToRemove = true;
1428 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001429
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001430 int outerDepth = parser.getDepth();
1431 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1432 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1433 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1434 continue;
1435 }
1436 String tag = parser.getName();
1437 if (TAG_NAME.equals(tag)) {
1438 type = parser.next();
1439 if (type == XmlPullParser.TEXT) {
1440 name = parser.getText();
1441 }
1442 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001443 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1444 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1445 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001446 }
1447 }
1448 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001449
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001450 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001451 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001452 userInfo.creationTime = creationTime;
1453 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001454 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001455 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001456 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001457 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001458 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001459 mBaseUserRestrictions.put(id, baseRestrictions);
1460 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001461 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001462 return userInfo;
1463
1464 } catch (IOException ioe) {
1465 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001466 } finally {
1467 if (fis != null) {
1468 try {
1469 fis.close();
1470 } catch (IOException e) {
1471 }
1472 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001473 }
1474 return null;
1475 }
1476
Amith Yamasani920ace02012-09-20 22:15:37 -07001477 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1478 String valueString = parser.getAttributeValue(null, attr);
1479 if (valueString == null) return defaultValue;
1480 try {
1481 return Integer.parseInt(valueString);
1482 } catch (NumberFormatException nfe) {
1483 return defaultValue;
1484 }
1485 }
1486
1487 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1488 String valueString = parser.getAttributeValue(null, attr);
1489 if (valueString == null) return defaultValue;
1490 try {
1491 return Long.parseLong(valueString);
1492 } catch (NumberFormatException nfe) {
1493 return defaultValue;
1494 }
1495 }
1496
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001497 private boolean isPackageInstalled(String pkg, int userId) {
1498 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1499 PackageManager.GET_UNINSTALLED_PACKAGES,
1500 userId);
1501 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1502 return false;
1503 }
1504 return true;
1505 }
1506
Amith Yamasanib82add22013-07-09 11:24:44 -07001507 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001508 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001509 * Does not do any permissions checking.
1510 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001511 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001512 synchronized (mPackagesLock) {
1513 File dir = Environment.getUserSystemDirectory(userId);
1514 String[] files = dir.list();
1515 if (files == null) return;
1516 for (String fileName : files) {
1517 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1518 File resFile = new File(dir, fileName);
1519 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001520 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001521 }
1522 }
1523 }
1524 }
1525 }
1526
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001527 /**
1528 * Removes the app restrictions file for a specific package and user id, if it exists.
1529 */
1530 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1531 synchronized (mPackagesLock) {
1532 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001533 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001534 if (resFile.exists()) {
1535 resFile.delete();
1536 }
1537 }
1538 }
1539
Kenny Guya52dc3e2014-02-11 15:33:14 +00001540 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001541 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001542 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001543 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001544 }
1545
Amith Yamasani258848d2012-08-10 17:06:33 -07001546 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001547 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001548 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001549 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001550 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001551
Jessica Hummelbe81c802014-04-22 15:49:22 +01001552 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001553 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001554 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1555 return null;
1556 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001557 if (ActivityManager.isLowRamDeviceStatic()) {
1558 return null;
1559 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001560 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001561 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001562 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001563 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001564 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001565 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001566 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001567 synchronized (mPackagesLock) {
1568 UserInfo parent = null;
1569 if (parentId != UserHandle.USER_NULL) {
1570 synchronized (mUsersLock) {
1571 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001572 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001573 if (parent == null) return null;
1574 }
1575 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1576 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1577 return null;
1578 }
1579 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1580 // If we're not adding a guest user or a managed profile and the limit has
1581 // been reached, cannot add a user.
1582 return null;
1583 }
1584 // If we're adding a guest and there already exists one, bail.
1585 if (isGuest && findCurrentGuestUser() != null) {
1586 return null;
1587 }
1588 // In legacy mode, restricted profile's parent can only be the owner user
1589 if (isRestricted && !UserManager.isSplitSystemUser()
1590 && (parentId != UserHandle.USER_SYSTEM)) {
1591 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1592 return null;
1593 }
1594 if (isRestricted && UserManager.isSplitSystemUser()) {
1595 if (parent == null) {
1596 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1597 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001598 return null;
1599 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001600 if (!parent.canHaveProfile()) {
1601 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1602 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001603 return null;
1604 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001605 }
1606 // In split system user mode, we assign the first human user the primary flag.
1607 // And if there is no device owner, we also assign the admin flag to primary user.
1608 if (UserManager.isSplitSystemUser()
1609 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1610 flags |= UserInfo.FLAG_PRIMARY;
1611 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1612 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1613 if (devicePolicyManager == null
1614 || devicePolicyManager.getDeviceOwner() == null) {
1615 flags |= UserInfo.FLAG_ADMIN;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001616 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001617 }
1618 userId = getNextAvailableId();
1619 userInfo = new UserInfo(userId, name, null, flags);
1620 userInfo.serialNumber = mNextSerialNumber++;
1621 long now = System.currentTimeMillis();
1622 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1623 userInfo.partial = true;
1624 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1625 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001626 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001627 }
1628 writeUserListLP();
1629 if (parent != null) {
1630 if (isManagedProfile) {
1631 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1632 parent.profileGroupId = parent.id;
1633 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001634 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001635 userInfo.profileGroupId = parent.profileGroupId;
1636 } else if (isRestricted) {
1637 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1638 parent.restrictedProfileParentId = parent.id;
1639 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001640 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001641 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001642 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001643 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001644 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001645 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1646 storage.createUserKey(userId, userInfo.serialNumber);
1647 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1648 final String volumeUuid = vol.getFsUuid();
1649 try {
1650 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1651 storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
1652 enforceSerialNumber(userDir, userInfo.serialNumber);
1653 } catch (IOException e) {
1654 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1655 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001656 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001657 mPm.createNewUser(userId);
1658 userInfo.partial = false;
1659 synchronized (mPackagesLock) {
1660 writeUserLP(userInfo);
1661 }
1662 updateUserIds();
1663 Bundle restrictions = new Bundle();
1664 synchronized (mRestrictionsLock) {
1665 mBaseUserRestrictions.append(userId, restrictions);
1666 }
1667 mPm.newUserCreated(userId);
1668 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1669 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1670 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1671 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001672 } finally {
1673 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001674 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001675 return userInfo;
1676 }
1677
Amith Yamasani0b285492011-04-14 17:35:23 -07001678 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001679 * @hide
1680 */
1681 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1682 checkManageUsersPermission("setupRestrictedProfile");
1683 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1684 if (user == null) {
1685 return null;
1686 }
1687 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1688 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1689 // the putIntForUser() will fail.
1690 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1691 android.provider.Settings.Secure.LOCATION_MODE,
1692 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1693 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1694 return user;
1695 }
1696
1697 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001698 * Find the current guest user. If the Guest user is partial,
1699 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001700 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001701 private UserInfo findCurrentGuestUser() {
1702 synchronized (mUsersLock) {
1703 final int size = mUsers.size();
1704 for (int i = 0; i < size; i++) {
1705 final UserInfo user = mUsers.valueAt(i);
1706 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1707 return user;
1708 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001709 }
1710 }
1711 return null;
1712 }
1713
1714 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001715 * Mark this guest user for deletion to allow us to create another guest
1716 * and switch to that user before actually removing this guest.
1717 * @param userHandle the userid of the current guest
1718 * @return whether the user could be marked for deletion
1719 */
1720 public boolean markGuestForDeletion(int userHandle) {
1721 checkManageUsersPermission("Only the system can remove users");
1722 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1723 UserManager.DISALLOW_REMOVE_USER, false)) {
1724 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1725 return false;
1726 }
1727
1728 long ident = Binder.clearCallingIdentity();
1729 try {
1730 final UserInfo user;
1731 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001732 synchronized (mUsersLock) {
1733 user = mUsers.get(userHandle);
1734 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1735 return false;
1736 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001737 }
1738 if (!user.isGuest()) {
1739 return false;
1740 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001741 // We set this to a guest user that is to be removed. This is a temporary state
1742 // where we are allowed to add new Guest users, even if this one is still not
1743 // removed. This user will still show up in getUserInfo() calls.
1744 // If we don't get around to removing this Guest user, it will be purged on next
1745 // startup.
1746 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001747 // Mark it as disabled, so that it isn't returned any more when
1748 // profiles are queried.
1749 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001750 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001751 }
1752 } finally {
1753 Binder.restoreCallingIdentity(ident);
1754 }
1755 return true;
1756 }
1757
1758 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001759 * Removes a user and all data directories created for that user. This method should be called
1760 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001761 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001762 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001763 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001764 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001765 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1766 UserManager.DISALLOW_REMOVE_USER, false)) {
1767 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1768 return false;
1769 }
1770
Kenny Guyee58b4f2014-05-23 15:19:53 +01001771 long ident = Binder.clearCallingIdentity();
1772 try {
1773 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001774 int currentUser = ActivityManager.getCurrentUser();
1775 if (currentUser == userHandle) {
1776 Log.w(LOG_TAG, "Current user cannot be removed");
1777 return false;
1778 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001779 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001780 synchronized (mUsersLock) {
1781 user = mUsers.get(userHandle);
1782 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1783 return false;
1784 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001785
Fyodor Kupolov82402752015-10-28 14:54:51 -07001786 // We remember deleted user IDs to prevent them from being
1787 // reused during the current boot; they can still be reused
1788 // after a reboot.
1789 mRemovingUserIds.put(userHandle, true);
1790 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001791
Kenny Guyee58b4f2014-05-23 15:19:53 +01001792 try {
1793 mAppOpsService.removeUser(userHandle);
1794 } catch (RemoteException e) {
1795 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1796 }
1797 // Set this to a partially created user, so that the user will be purged
1798 // on next startup, in case the runtime stops now before stopping and
1799 // removing the user completely.
1800 user.partial = true;
1801 // Mark it as disabled, so that it isn't returned any more when
1802 // profiles are queried.
1803 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001804 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001805 }
1806
1807 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1808 && user.isManagedProfile()) {
1809 // Send broadcast to notify system that the user removed was a
1810 // managed user.
1811 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1812 }
1813
1814 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1815 int res;
1816 try {
1817 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1818 new IStopUserCallback.Stub() {
1819 @Override
1820 public void userStopped(int userId) {
1821 finishRemoveUser(userId);
1822 }
1823 @Override
1824 public void userStopAborted(int userId) {
1825 }
1826 });
1827 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001828 return false;
1829 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001830 return res == ActivityManager.USER_OP_SUCCESS;
1831 } finally {
1832 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001833 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001834 }
1835
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001836 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001837 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001838 // Let other services shutdown any activity and clean up their state before completely
1839 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001840 long ident = Binder.clearCallingIdentity();
1841 try {
1842 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1843 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001844 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1845 android.Manifest.permission.MANAGE_USERS,
1846
1847 new BroadcastReceiver() {
1848 @Override
1849 public void onReceive(Context context, Intent intent) {
1850 if (DBG) {
1851 Slog.i(LOG_TAG,
1852 "USER_REMOVED broadcast sent, cleaning up user data "
1853 + userHandle);
1854 }
1855 new Thread() {
1856 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001857 // Clean up any ActivityManager state
1858 LocalServices.getService(ActivityManagerInternal.class)
1859 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001860 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001861 }
1862 }.start();
1863 }
1864 },
1865
1866 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001867 } finally {
1868 Binder.restoreCallingIdentity(ident);
1869 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001870 }
1871
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001872 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001873 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001874 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001875 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001876
1877 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001878 synchronized (mUsersLock) {
1879 mUsers.remove(userHandle);
1880 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001881 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001882 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001883 userFile.delete();
1884 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001885 synchronized (mPackagesLock) {
1886 writeUserListLP();
1887 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001888 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001889 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1890 }
1891
Amith Yamasani61f57372012-08-31 12:12:28 -07001892 private void removeDirectoryRecursive(File parent) {
1893 if (parent.isDirectory()) {
1894 String[] files = parent.list();
1895 for (String filename : files) {
1896 File child = new File(parent, filename);
1897 removeDirectoryRecursive(child);
1898 }
1899 }
1900 parent.delete();
1901 }
1902
Kenny Guyf8d3a232014-05-15 16:09:52 +01001903 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001904 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001905 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1906 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001907 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1908 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001909 }
1910
Amith Yamasani2a003292012-08-14 18:25:45 -07001911 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001912 public Bundle getApplicationRestrictions(String packageName) {
1913 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1914 }
1915
1916 @Override
1917 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001918 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001919 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001920 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001921 }
1922 synchronized (mPackagesLock) {
1923 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001924 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001925 }
1926 }
1927
1928 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001929 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001930 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001931 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001932 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001933 if (restrictions == null || restrictions.isEmpty()) {
1934 cleanAppRestrictionsForPackage(packageName, userId);
1935 } else {
1936 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001937 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001938 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001939 }
Robin Lee66e5d962014-04-09 16:44:21 +01001940
Kenny Guyd21b2182014-07-17 16:38:55 +01001941 if (isPackageInstalled(packageName, userId)) {
1942 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1943 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1944 changeIntent.setPackage(packageName);
1945 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1946 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1947 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001948 }
1949
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001950 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001951 mHandler.post(new Runnable() {
1952 @Override
1953 public void run() {
1954 List<ApplicationInfo> apps =
1955 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1956 userHandle).getList();
1957 final long ident = Binder.clearCallingIdentity();
1958 try {
1959 for (ApplicationInfo appInfo : apps) {
1960 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001961 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1962 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001963 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001964 userHandle);
1965 }
1966 }
1967 } finally {
1968 Binder.restoreCallingIdentity(ident);
1969 }
1970 }
1971 });
1972 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001973 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001974 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001975 try {
1976 return mContext.getPackageManager().getApplicationInfo(packageName,
1977 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1978 } catch (NameNotFoundException nnfe) {
1979 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001980 } finally {
1981 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001982 }
1983 }
1984
Fyodor Kupolov82402752015-10-28 14:54:51 -07001985 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001986 AtomicFile restrictionsFile =
1987 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1988 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001989 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001990 }
1991
1992 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001993 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001994 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001995 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001996 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001997 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001998 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001999
2000 FileInputStream fis = null;
2001 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002002 fis = restrictionsFile.openRead();
2003 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002004 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002005 XmlUtils.nextElement(parser);
2006 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002007 Slog.e(LOG_TAG, "Unable to read restrictions file "
2008 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002009 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002010 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002011 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2012 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002013 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002014 } catch (IOException|XmlPullParserException e) {
2015 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002016 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002017 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002018 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002019 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002020 }
2021
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002022 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2023 XmlPullParser parser) throws XmlPullParserException, IOException {
2024 int type = parser.getEventType();
2025 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2026 String key = parser.getAttributeValue(null, ATTR_KEY);
2027 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2028 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2029 if (multiple != null) {
2030 values.clear();
2031 int count = Integer.parseInt(multiple);
2032 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2033 if (type == XmlPullParser.START_TAG
2034 && parser.getName().equals(TAG_VALUE)) {
2035 values.add(parser.nextText().trim());
2036 count--;
2037 }
2038 }
2039 String [] valueStrings = new String[values.size()];
2040 values.toArray(valueStrings);
2041 restrictions.putStringArray(key, valueStrings);
2042 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2043 restrictions.putBundle(key, readBundleEntry(parser, values));
2044 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2045 final int outerDepth = parser.getDepth();
2046 ArrayList<Bundle> bundleList = new ArrayList<>();
2047 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2048 Bundle childBundle = readBundleEntry(parser, values);
2049 bundleList.add(childBundle);
2050 }
2051 restrictions.putParcelableArray(key,
2052 bundleList.toArray(new Bundle[bundleList.size()]));
2053 } else {
2054 String value = parser.nextText().trim();
2055 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2056 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2057 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2058 restrictions.putInt(key, Integer.parseInt(value));
2059 } else {
2060 restrictions.putString(key, value);
2061 }
2062 }
2063 }
2064 }
2065
2066 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2067 throws IOException, XmlPullParserException {
2068 Bundle childBundle = new Bundle();
2069 final int outerDepth = parser.getDepth();
2070 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2071 readEntry(childBundle, values, parser);
2072 }
2073 return childBundle;
2074 }
2075
Fyodor Kupolov82402752015-10-28 14:54:51 -07002076 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002077 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002078 AtomicFile restrictionsFile = new AtomicFile(
2079 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002080 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002081 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002082 }
2083
2084 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002085 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002086 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002087 try {
2088 fos = restrictionsFile.startWrite();
2089 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2090
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002091 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002092 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002093 serializer.startDocument(null, true);
2094 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2095
2096 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002097 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002098 serializer.endTag(null, TAG_RESTRICTIONS);
2099
2100 serializer.endDocument();
2101 restrictionsFile.finishWrite(fos);
2102 } catch (Exception e) {
2103 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002104 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2105 }
2106 }
2107
2108 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2109 throws IOException {
2110 for (String key : restrictions.keySet()) {
2111 Object value = restrictions.get(key);
2112 serializer.startTag(null, TAG_ENTRY);
2113 serializer.attribute(null, ATTR_KEY, key);
2114
2115 if (value instanceof Boolean) {
2116 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2117 serializer.text(value.toString());
2118 } else if (value instanceof Integer) {
2119 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2120 serializer.text(value.toString());
2121 } else if (value == null || value instanceof String) {
2122 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2123 serializer.text(value != null ? (String) value : "");
2124 } else if (value instanceof Bundle) {
2125 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2126 writeBundle((Bundle) value, serializer);
2127 } else if (value instanceof Parcelable[]) {
2128 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2129 Parcelable[] array = (Parcelable[]) value;
2130 for (Parcelable parcelable : array) {
2131 if (!(parcelable instanceof Bundle)) {
2132 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2133 }
2134 serializer.startTag(null, TAG_ENTRY);
2135 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2136 writeBundle((Bundle) parcelable, serializer);
2137 serializer.endTag(null, TAG_ENTRY);
2138 }
2139 } else {
2140 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2141 String[] values = (String[]) value;
2142 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2143 for (String choice : values) {
2144 serializer.startTag(null, TAG_VALUE);
2145 serializer.text(choice != null ? choice : "");
2146 serializer.endTag(null, TAG_VALUE);
2147 }
2148 }
2149 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002150 }
2151 }
2152
2153 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002154 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002155 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002156 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002157 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002158 }
2159 }
2160
2161 @Override
2162 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002163 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002164 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002165 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002166 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002167 }
2168 // Not found
2169 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002170 }
2171 }
2172
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002173 @Override
2174 public long getUserCreationTime(int userHandle) {
2175 int callingUserId = UserHandle.getCallingUserId();
2176 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002177 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002178 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002179 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002180 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002181 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002182 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002183 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002184 }
2185 }
2186 }
2187 if (userInfo == null) {
2188 throw new SecurityException("userHandle can only be the calling user or a managed "
2189 + "profile associated with this user");
2190 }
2191 return userInfo.creationTime;
2192 }
2193
Amith Yamasani0b285492011-04-14 17:35:23 -07002194 /**
2195 * Caches the list of user ids in an array, adjusting the array size when necessary.
2196 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002197 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002198 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002199 synchronized (mUsersLock) {
2200 final int userSize = mUsers.size();
2201 for (int i = 0; i < userSize; i++) {
2202 if (!mUsers.valueAt(i).partial) {
2203 num++;
2204 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002205 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002206 final int[] newUsers = new int[num];
2207 int n = 0;
2208 for (int i = 0; i < userSize; i++) {
2209 if (!mUsers.valueAt(i).partial) {
2210 newUsers[n++] = mUsers.keyAt(i);
2211 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002212 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002213 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002214 }
2215 }
2216
2217 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002218 * Called right before a user starts. This will not be called for the system user.
2219 */
2220 public void onBeforeStartUser(int userId) {
2221 synchronized (mRestrictionsLock) {
2222 applyUserRestrictionsLR(userId);
2223 }
2224 }
2225
2226 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002227 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002228 * @param userId the user that was just foregrounded
2229 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002230 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002231 UserInfo user = getUserInfoNoChecks(userId);
2232 if (user == null || user.partial) {
2233 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2234 return;
2235 }
2236 long now = System.currentTimeMillis();
2237 if (now > EPOCH_PLUS_30_YEARS) {
2238 user.lastLoggedInTime = now;
2239 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002240 }
2241 }
2242
2243 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002244 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002245 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2246 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002247 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002248 private int getNextAvailableId() {
2249 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002250 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002251 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002252 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002253 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002254 }
2255 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002256 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002257 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002258 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002259 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002260
Amith Yamasanifc95e702013-09-26 13:20:17 -07002261 private String packageToRestrictionsFileName(String packageName) {
2262 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2263 }
2264
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002265 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002266 * Enforce that serial number stored in user directory inode matches the
2267 * given expected value. Gracefully sets the serial number if currently
2268 * undefined.
2269 *
2270 * @throws IOException when problem extracting serial number, or serial
2271 * number is mismatched.
2272 */
2273 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2274 final int foundSerial = getSerialNumber(file);
2275 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2276
2277 if (foundSerial == -1) {
2278 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2279 try {
2280 setSerialNumber(file, serialNumber);
2281 } catch (IOException e) {
2282 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2283 }
2284
2285 } else if (foundSerial != serialNumber) {
2286 throw new IOException("Found serial number " + foundSerial
2287 + " doesn't match expected " + serialNumber);
2288 }
2289 }
2290
2291 /**
2292 * Set serial number stored in user directory inode.
2293 *
2294 * @throws IOException if serial number was already set
2295 */
2296 private static void setSerialNumber(File file, int serialNumber)
2297 throws IOException {
2298 try {
2299 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2300 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2301 } catch (ErrnoException e) {
2302 throw e.rethrowAsIOException();
2303 }
2304 }
2305
2306 /**
2307 * Return serial number stored in user directory inode.
2308 *
2309 * @return parsed serial number, or -1 if not set
2310 */
2311 private static int getSerialNumber(File file) throws IOException {
2312 try {
2313 final byte[] buf = new byte[256];
2314 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2315 final String serial = new String(buf, 0, len);
2316 try {
2317 return Integer.parseInt(serial);
2318 } catch (NumberFormatException e) {
2319 throw new IOException("Bad serial number: " + serial);
2320 }
2321 } catch (ErrnoException e) {
2322 if (e.errno == OsConstants.ENODATA) {
2323 return -1;
2324 } else {
2325 throw e.rethrowAsIOException();
2326 }
2327 }
2328 }
2329
Amith Yamasani920ace02012-09-20 22:15:37 -07002330 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002331 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2332 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2333 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2334 }
2335
2336 int onShellCommand(Shell shell, String cmd) {
2337 if (cmd == null) {
2338 return shell.handleDefaultCommands(cmd);
2339 }
2340
2341 final PrintWriter pw = shell.getOutPrintWriter();
2342 try {
2343 switch(cmd) {
2344 case "list":
2345 return runList(pw);
2346 }
2347 } catch (RemoteException e) {
2348 pw.println("Remote exception: " + e);
2349 }
2350 return -1;
2351 }
2352
2353 private int runList(PrintWriter pw) throws RemoteException {
2354 final IActivityManager am = ActivityManagerNative.getDefault();
2355 final List<UserInfo> users = getUsers(false);
2356 if (users == null) {
2357 pw.println("Error: couldn't get users");
2358 return 1;
2359 } else {
2360 pw.println("Users:");
2361 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002362 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002363 pw.println("\t" + users.get(i).toString() + running);
2364 }
2365 return 0;
2366 }
2367 }
2368
2369 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002370 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2371 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2372 != PackageManager.PERMISSION_GRANTED) {
2373 pw.println("Permission Denial: can't dump UserManager from from pid="
2374 + Binder.getCallingPid()
2375 + ", uid=" + Binder.getCallingUid()
2376 + " without permission "
2377 + android.Manifest.permission.DUMP);
2378 return;
2379 }
2380
2381 long now = System.currentTimeMillis();
2382 StringBuilder sb = new StringBuilder();
2383 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002384 synchronized (mUsersLock) {
2385 pw.println("Users:");
2386 for (int i = 0; i < mUsers.size(); i++) {
2387 UserInfo user = mUsers.valueAt(i);
2388 if (user == null) {
2389 continue;
2390 }
2391 pw.print(" "); pw.print(user);
2392 pw.print(" serialNo="); pw.print(user.serialNumber);
2393 if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2394 pw.print(" <removing> ");
2395 }
2396 if (user.partial) {
2397 pw.print(" <partial>");
2398 }
2399 pw.println();
2400 pw.print(" Created: ");
2401 if (user.creationTime == 0) {
2402 pw.println("<unknown>");
2403 } else {
2404 sb.setLength(0);
2405 TimeUtils.formatDuration(now - user.creationTime, sb);
2406 sb.append(" ago");
2407 pw.println(sb);
2408 }
2409 pw.print(" Last logged in: ");
2410 if (user.lastLoggedInTime == 0) {
2411 pw.println("<unknown>");
2412 } else {
2413 sb.setLength(0);
2414 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2415 sb.append(" ago");
2416 pw.println(sb);
2417 }
2418 pw.println(" Restrictions:");
2419 synchronized (mRestrictionsLock) {
2420 UserRestrictionsUtils.dumpRestrictions(
2421 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002422 pw.println(" Device policy local restrictions:");
2423 UserRestrictionsUtils.dumpRestrictions(
2424 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002425 pw.println(" Effective restrictions:");
2426 UserRestrictionsUtils.dumpRestrictions(
2427 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2428 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002429 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002430 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002431 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002432 pw.println(" Device policy global restrictions:");
2433 synchronized (mRestrictionsLock) {
2434 UserRestrictionsUtils
2435 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2436 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002437 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002438 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002439 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002440 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002441 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002442 }
2443 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002444
2445 final class MainHandler extends Handler {
2446
2447 @Override
2448 public void handleMessage(Message msg) {
2449 switch (msg.what) {
2450 case WRITE_USER_MSG:
2451 removeMessages(WRITE_USER_MSG, msg.obj);
2452 synchronized (mPackagesLock) {
2453 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002454 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002455 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002456 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002457 }
2458 }
2459 }
2460 }
2461 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002462
2463 /**
2464 * @param userId
2465 * @return whether the user has been initialized yet
2466 */
2467 boolean isInitialized(int userId) {
2468 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2469 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002470
2471 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002472 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002473 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2474 @Nullable Bundle globalRestrictions) {
2475 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2476 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002477 }
2478
2479 @Override
2480 public Bundle getBaseUserRestrictions(int userId) {
2481 synchronized (mRestrictionsLock) {
2482 return mBaseUserRestrictions.get(userId);
2483 }
2484 }
2485
2486 @Override
2487 public void setBaseUserRestrictionsByDpmsForMigration(
2488 int userId, Bundle baseRestrictions) {
2489 synchronized (mRestrictionsLock) {
2490 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002491 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002492 }
2493
Fyodor Kupolov82402752015-10-28 14:54:51 -07002494 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002495 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002496 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002497 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002498 } else {
2499 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2500 }
2501 }
2502 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002503
2504 @Override
2505 public boolean getUserRestriction(int userId, String key) {
2506 return getUserRestrictions(userId).getBoolean(key);
2507 }
2508
2509 @Override
2510 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2511 synchronized (mUserRestrictionsListeners) {
2512 mUserRestrictionsListeners.add(listener);
2513 }
2514 }
2515
2516 @Override
2517 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2518 synchronized (mUserRestrictionsListeners) {
2519 mUserRestrictionsListeners.remove(listener);
2520 }
2521 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002522 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002523
2524 private class Shell extends ShellCommand {
2525 @Override
2526 public int onCommand(String cmd) {
2527 return onShellCommand(this, cmd);
2528 }
2529
2530 @Override
2531 public void onHelp() {
2532 final PrintWriter pw = getOutPrintWriter();
2533 pw.println("User manager (user) commands:");
2534 pw.println(" help");
2535 pw.println(" Print this help text.");
2536 pw.println("");
2537 pw.println(" list");
2538 pw.println(" Prints all users on the system.");
2539 }
2540 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002541
2542 private static void debug(String message) {
2543 Log.d(LOG_TAG, message +
2544 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2545 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002546}