blob: b7dfa9b054b858040c67d42e9d737ff78355c64a [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chen594f2082015-08-18 11:04:20 -070019import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070020import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070023import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070024import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070025import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070026import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070027import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070031import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070032import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080033import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070035import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080038import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070039import android.os.Environment;
40import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080041import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080043import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010044import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070045import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070047import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070048import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040049import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070050import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070051import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070052import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070053import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080054import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010055import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070056import android.os.storage.VolumeInfo;
57import android.system.ErrnoException;
58import android.system.Os;
59import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070060import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070061import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import android.util.Slog;
63import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080064import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070065import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import android.util.Xml;
67
Makoto Onuki068c54a2015-10-13 14:34:03 -070068import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070069import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040070import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080071import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070072import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070073import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070074import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080075
76import org.xmlpull.v1.XmlPullParser;
77import org.xmlpull.v1.XmlPullParserException;
78import org.xmlpull.v1.XmlSerializer;
79
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import java.io.BufferedOutputStream;
81import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070082import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070084import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import java.io.FileOutputStream;
86import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070087import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010088import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070089import java.util.ArrayList;
90import java.util.List;
91
Fyodor Kupolov262f9952015-03-23 18:55:11 -070092import libcore.io.IoUtils;
93
Makoto Onuki068c54a2015-10-13 14:34:03 -070094/**
95 * Service for {@link UserManager}.
96 *
97 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -070098 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -080099 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700100 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
101 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
102 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700103 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700104public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700105 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800106 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
107 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700108
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700111 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700113 private static final String ATTR_CREATION_TIME = "created";
114 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700115 private static final String ATTR_SERIAL_NO = "serialNumber";
116 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700117 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700118 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700119 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100120 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700121 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530122 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800125 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800126 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800127 private static final String TAG_ENTRY = "entry";
128 private static final String TAG_VALUE = "value";
129 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700130 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800131 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700133 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
134 private static final String ATTR_TYPE_STRING = "s";
135 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700136 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700137 private static final String ATTR_TYPE_BUNDLE = "B";
138 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700139
Amith Yamasani0b285492011-04-14 17:35:23 -0700140 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700142 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100143 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800145 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700146 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800147
Amith Yamasani634cf312012-10-04 17:34:21 -0700148 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700149 // We need to keep process uid within Integer.MAX_VALUE.
150 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700151
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700152 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700153
Amith Yamasani920ace02012-09-20 22:15:37 -0700154 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
155
Nicolas Prevotb8186812015-08-06 15:00:03 +0100156 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700157 // without first making sure that the rest of the framework is prepared for it.
158 private static final int MAX_MANAGED_PROFILES = 1;
159
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800160 static final int WRITE_USER_MSG = 1;
161 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530162
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700163 private static final String XATTR_SERIAL = "user.serial";
164
Dianne Hackborn4428e172012-08-24 17:43:05 -0700165 private final Context mContext;
166 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700167 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700168 // Short-term lock for internal state, when interaction/sync with PM is not required
169 private final Object mUsersLock = new Object();
170 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800172 private final Handler mHandler;
173
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700174 private final File mUsersDir;
175 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700176
Fyodor Kupolov82402752015-10-28 14:54:51 -0700177 @GuardedBy("mUsersLock")
178 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700179
180 /**
181 * User restrictions set via UserManager. This doesn't include restrictions set by
182 * device owner / profile owners.
183 *
184 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
185 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
186 * maybe shared between {@link #mBaseUserRestrictions} and
187 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
188 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700189 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700190 */
191 @GuardedBy("mRestrictionsLock")
192 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
193
194 /**
195 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
196 * with device / profile owner restrictions. We'll initialize it lazily; use
197 * {@link #getEffectiveUserRestrictions} to access it.
198 *
199 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
200 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
201 * maybe shared between {@link #mBaseUserRestrictions} and
202 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
203 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700204 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700205 */
206 @GuardedBy("mRestrictionsLock")
207 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
208
Makoto Onuki4f160732015-10-27 17:15:38 -0700209 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800210 * User restrictions that have already been applied in
211 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
212 * that have changed since the last
213 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700214 */
215 @GuardedBy("mRestrictionsLock")
216 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
217
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800218 /**
219 * User restrictions set by {@link DevicePolicyManager} that should be applied to all users,
220 * including guests.
221 */
222 @GuardedBy("mRestrictionsLock")
223 private Bundle mDevicePolicyGlobalUserRestrictions;
224
225 /**
226 * User restrictions set by {@link DevicePolicyManager} for each user.
227 */
228 @GuardedBy("mRestrictionsLock")
229 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
230
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800231 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530232 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800233
234 /**
235 * Set of user IDs being actively removed. Removed IDs linger in this set
236 * for several seconds to work around a VFS caching issue.
237 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700238 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800239 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700240
Fyodor Kupolov82402752015-10-28 14:54:51 -0700241 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700242 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800243 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700244 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700245 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700246
Jason Monk62062992014-05-06 09:55:28 -0400247 private IAppOpsService mAppOpsService;
248
Makoto Onuki068c54a2015-10-13 14:34:03 -0700249 private final LocalService mLocalService;
250
Makoto Onukid45a4a22015-11-02 17:17:38 -0800251 @GuardedBy("mUserRestrictionsListeners")
252 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
253 new ArrayList<>();
254
Amith Yamasani258848d2012-08-10 17:06:33 -0700255 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700256
Dianne Hackborn4428e172012-08-24 17:43:05 -0700257 public static UserManagerService getInstance() {
258 synchronized (UserManagerService.class) {
259 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700260 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700261 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700262
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800263 @VisibleForTesting
264 UserManagerService(File dataDir) {
265 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700266 }
267
Dianne Hackborn4428e172012-08-24 17:43:05 -0700268 /**
269 * Called by package manager to create the service. This is closely
270 * associated with the package manager, and the given lock is the
271 * package manager's own lock.
272 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800273 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
274 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700275 }
276
Dianne Hackborn4428e172012-08-24 17:43:05 -0700277 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800278 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700279 mContext = context;
280 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700281 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800282 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800283 synchronized (mPackagesLock) {
284 mUsersDir = new File(dataDir, USER_INFO_DIR);
285 mUsersDir.mkdirs();
286 // Make zeroth user directory, for services to migrate their files to that location
287 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
288 userZeroDir.mkdirs();
289 FileUtils.setPermissions(mUsersDir.toString(),
290 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
291 -1, -1);
292 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
293 initDefaultGuestRestrictions();
294 readUserListLP();
295 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700296 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700297 mLocalService = new LocalService();
298 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700299 }
300
301 void systemReady() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800302 // Prune out any partially created/partially removed users.
303 ArrayList<UserInfo> partials = new ArrayList<>();
304 synchronized (mUsersLock) {
305 final int userSize = mUsers.size();
306 for (int i = 0; i < userSize; i++) {
307 UserInfo ui = mUsers.valueAt(i);
308 if ((ui.partial || ui.guestToRemove) && i != 0) {
309 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700310 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700311 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700312 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800313 final int partialsSize = partials.size();
314 for (int i = 0; i < partialsSize; i++) {
315 UserInfo ui = partials.get(i);
316 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
317 + " (name=" + ui.name + ")");
318 removeUserState(ui.id);
319 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800320
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700321 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800322
Jason Monk62062992014-05-06 09:55:28 -0400323 mAppOpsService = IAppOpsService.Stub.asInterface(
324 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800325
326 synchronized (mRestrictionsLock) {
327 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400328 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700329 }
330
331 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700332 public UserInfo getPrimaryUser() {
333 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700334 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700335 final int userSize = mUsers.size();
336 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700337 UserInfo ui = mUsers.valueAt(i);
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800338 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700339 return ui;
340 }
341 }
342 }
343 return null;
344 }
345
346 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700347 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700348 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700349 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700350 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700351 final int userSize = mUsers.size();
352 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700353 UserInfo ui = mUsers.valueAt(i);
354 if (ui.partial) {
355 continue;
356 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800357 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700358 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700359 }
Amith Yamasani13593602012-03-22 16:16:17 -0700360 }
361 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700362 }
Amith Yamasani13593602012-03-22 16:16:17 -0700363 }
364
Amith Yamasani258848d2012-08-10 17:06:33 -0700365 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100366 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800367 if (userId != UserHandle.getCallingUserId()) {
368 checkManageUsersPermission("getting profiles related to user " + userId);
369 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700370 final long ident = Binder.clearCallingIdentity();
371 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700372 synchronized (mUsersLock) {
373 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100374 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700375 } finally {
376 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000377 }
378 }
379
Amith Yamasanibe465322014-04-24 13:45:17 -0700380 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700381 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
382 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700383 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700384 if (user == null) {
385 // Probably a dying user
386 return users;
387 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700388 final int userSize = mUsers.size();
389 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700390 UserInfo profile = mUsers.valueAt(i);
391 if (!isProfileOf(user, profile)) {
392 continue;
393 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100394 if (enabledOnly && !profile.isEnabled()) {
395 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700396 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700397 if (mRemovingUserIds.get(profile.id)) {
398 continue;
399 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700400 users.add(profile);
401 }
402 return users;
403 }
404
Jessica Hummelbe81c802014-04-22 15:49:22 +0100405 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700406 public int getCredentialOwnerProfile(int userHandle) {
407 checkManageUsersPermission("get the credential owner");
Jeff Sharkeyba512352015-11-12 20:17:45 -0800408 if (!StorageManager.isFileBasedEncryptionEnabled()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700409 synchronized (mUsersLock) {
410 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700411 if (profileParent != null) {
412 return profileParent.id;
413 }
414 }
415 }
416
417 return userHandle;
418 }
419
420 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700421 public boolean isSameProfileGroup(int userId, int otherUserId) {
422 if (userId == otherUserId) return true;
423 checkManageUsersPermission("check if in the same profile group");
424 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700425 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700426 }
427 }
428
Fyodor Kupolov82402752015-10-28 14:54:51 -0700429 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
430 synchronized (mUsersLock) {
431 UserInfo userInfo = getUserInfoLU(userId);
432 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
433 return false;
434 }
435 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
436 if (otherUserInfo == null
437 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
438 return false;
439 }
440 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700441 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700442 }
443
444 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100445 public UserInfo getProfileParent(int userHandle) {
446 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700447 synchronized (mUsersLock) {
448 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700449 }
450 }
451
Fyodor Kupolov82402752015-10-28 14:54:51 -0700452 private UserInfo getProfileParentLU(int userHandle) {
453 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700454 if (profile == null) {
455 return null;
456 }
457 int parentUserId = profile.profileGroupId;
458 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
459 return null;
460 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700461 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100462 }
463 }
464
Fyodor Kupolov82402752015-10-28 14:54:51 -0700465 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100466 return user.id == profile.id ||
467 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
468 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000469 }
470
471 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100472 public void setUserEnabled(int userId) {
473 checkManageUsersPermission("enable user");
474 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700475 UserInfo info;
476 synchronized (mUsersLock) {
477 info = getUserInfoLU(userId);
478 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100479 if (info != null && !info.isEnabled()) {
480 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700481 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100482 }
483 }
484 }
485
486 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700487 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700488 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700489 synchronized (mUsersLock) {
490 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700491 }
492 }
493
Amith Yamasani71e6c692013-03-24 17:39:28 -0700494 @Override
495 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700496 synchronized (mUsersLock) {
497 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700498 }
499 }
500
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700501 @Override
502 public boolean canHaveRestrictedProfile(int userId) {
503 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700504 synchronized (mUsersLock) {
505 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700506 if (userInfo == null || !userInfo.canHaveProfile()) {
507 return false;
508 }
509 if (!userInfo.isAdmin()) {
510 return false;
511 }
512 }
513 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
514 Context.DEVICE_POLICY_SERVICE);
515 // restricted profile can be created if there is no DO set and the admin user has no PO
Makoto Onukic8a5a552015-11-19 14:29:12 -0800516 return !dpm.isDeviceManaged() && dpm.getProfileOwnerAsUser(userId) == null;
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700517 }
518
Amith Yamasani195263742012-08-21 15:40:12 -0700519 /*
520 * Should be locked on mUsers before calling this.
521 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700522 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700523 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700524 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800525 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700526 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
527 return null;
528 }
529 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700530 }
531
Fyodor Kupolov82402752015-10-28 14:54:51 -0700532 /**
533 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
534 * <p>No permissions checking or any addition checks are made</p>
535 */
536 private UserInfo getUserInfoNoChecks(int userId) {
537 synchronized (mUsersLock) {
538 return mUsers.get(userId);
539 }
540 }
541
Amith Yamasani236b2b52015-08-18 14:32:14 -0700542 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700543 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700544 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700545 }
546
Amith Yamasani258848d2012-08-10 17:06:33 -0700547 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700548 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700549 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700550 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700551 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700552 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700553 if (info == null || info.partial) {
554 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
555 return;
556 }
Amith Yamasani13593602012-03-22 16:16:17 -0700557 if (name != null && !name.equals(info.name)) {
558 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700559 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700560 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700561 }
562 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700563 if (changed) {
564 sendUserInfoChangedBroadcast(userId);
565 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700566 }
567
Amith Yamasani258848d2012-08-10 17:06:33 -0700568 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700569 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700570 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400571 long ident = Binder.clearCallingIdentity();
572 try {
573 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700574 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400575 if (info == null || info.partial) {
576 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
577 return;
578 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700579 writeBitmapLP(info, bitmap);
580 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700581 }
Jason Monk9a944532014-07-08 09:31:21 -0400582 sendUserInfoChangedBroadcast(userId);
583 } finally {
584 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700585 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700586 }
587
588 private void sendUserInfoChangedBroadcast(int userId) {
589 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
590 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
591 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700592 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700593 }
594
Amith Yamasani258848d2012-08-10 17:06:33 -0700595 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100596 public ParcelFileDescriptor getUserIcon(int userId) {
597 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700598 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700599 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700600 if (info == null || info.partial) {
601 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
602 return null;
603 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700604 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100605 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
606 || callingGroupId != info.profileGroupId) {
607 checkManageUsersPermission("get the icon of a user who is not related");
608 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700609 if (info.iconPath == null) {
610 return null;
611 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100612 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700613 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100614
615 try {
616 return ParcelFileDescriptor.open(
617 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
618 } catch (FileNotFoundException e) {
619 Log.e(LOG_TAG, "Couldn't find icon file", e);
620 }
621 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700622 }
623
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700624 public void makeInitialized(int userId) {
625 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800626 boolean scheduleWriteUser = false;
627 UserInfo info;
628 synchronized (mUsersLock) {
629 info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700630 if (info == null || info.partial) {
631 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800632 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700633 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800634 if ((info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700635 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800636 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700637 }
638 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800639 if (scheduleWriteUser) {
640 scheduleWriteUser(info);
641 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700642 }
643
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700644 /**
645 * If default guest restrictions haven't been initialized yet, add the basic
646 * restrictions.
647 */
648 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800649 synchronized (mGuestRestrictions) {
650 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800651 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800652 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
653 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
654 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700655 }
656 }
657
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800658 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530659 public Bundle getDefaultGuestRestrictions() {
660 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800661 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530662 return new Bundle(mGuestRestrictions);
663 }
664 }
665
666 @Override
667 public void setDefaultGuestRestrictions(Bundle restrictions) {
668 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800669 synchronized (mGuestRestrictions) {
670 mGuestRestrictions.clear();
671 mGuestRestrictions.putAll(restrictions);
672 }
673 synchronized (mPackagesLock) {
674 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530675 }
676 }
677
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800678 /**
679 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
680 */
681 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
682 @Nullable Bundle global) {
683 Preconditions.checkNotNull(local);
684 boolean globalChanged = false;
685 boolean localChanged;
686 synchronized (mRestrictionsLock) {
687 if (global != null) {
688 // Update global.
689 globalChanged = !UserRestrictionsUtils.areEqual(
690 mDevicePolicyGlobalUserRestrictions, global);
691 if (globalChanged) {
692 mDevicePolicyGlobalUserRestrictions = global;
693 }
694 }
695 {
696 // Update local.
697 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
698 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
699 if (localChanged) {
700 mDevicePolicyLocalUserRestrictions.put(userId, local);
701 }
702 }
703 }
704 if (DBG) {
705 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
706 + " global=" + global + (globalChanged ? " (changed)" : "")
707 + " local=" + local + (localChanged ? " (changed)" : "")
708 );
709 }
710 // Don't call them within the mRestrictionsLock.
711 synchronized (mPackagesLock) {
712 if (globalChanged) {
713 writeUserListLP();
714 }
715 if (localChanged) {
716 writeUserLP(getUserInfoNoChecks(userId));
717 }
718 }
719
720 synchronized (mRestrictionsLock) {
721 if (globalChanged) {
722 applyUserRestrictionsForAllUsersLR();
723 } else if (localChanged) {
724 applyUserRestrictionsLR(userId);
725 }
726 }
727 }
728
Makoto Onuki068c54a2015-10-13 14:34:03 -0700729 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700730 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800731 final Bundle baseRestrictions =
732 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
733 final Bundle global = mDevicePolicyGlobalUserRestrictions;
734 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700735
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800736 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
737 // Common case first.
738 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700739 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800740 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
741 UserRestrictionsUtils.merge(effective, global);
742 UserRestrictionsUtils.merge(effective, local);
743
Makoto Onuki068c54a2015-10-13 14:34:03 -0700744 return effective;
745 }
746
747 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700748 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700749 if (DBG) {
750 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
751 }
752 mCachedEffectiveUserRestrictions.remove(userId);
753 }
754
755 private Bundle getEffectiveUserRestrictions(int userId) {
756 synchronized (mRestrictionsLock) {
757 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
758 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700759 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700760 mCachedEffectiveUserRestrictions.put(userId, restrictions);
761 }
762 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700763 }
764 }
765
Makoto Onuki068c54a2015-10-13 14:34:03 -0700766 /** @return a specific user restriction that's in effect currently. */
767 @Override
768 public boolean hasUserRestriction(String restrictionKey, int userId) {
769 Bundle restrictions = getEffectiveUserRestrictions(userId);
770 return restrictions != null && restrictions.getBoolean(restrictionKey);
771 }
772
773 /**
774 * @return UserRestrictions that are in effect currently. This always returns a new
775 * {@link Bundle}.
776 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700777 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800778 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800779 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800780 }
781
782 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700783 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700784 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700785 synchronized (mRestrictionsLock) {
786 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
787 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800788 final Bundle newRestrictions = UserRestrictionsUtils.clone(
789 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700790 newRestrictions.putBoolean(key, value);
791
Fyodor Kupolov82402752015-10-28 14:54:51 -0700792 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700793 }
794 }
795
Makoto Onuki068c54a2015-10-13 14:34:03 -0700796 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800797 * Optionally updating user restrictions, calculate the effective user restrictions and also
798 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700799 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800800 * @param newRestrictions User restrictions to set.
801 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700802 * @param userId target user ID.
803 */
804 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700805 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700806 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800807
808 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
809 mAppliedUserRestrictions.get(userId));
810
811 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700812 if (newRestrictions != null) {
813 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800814 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
815
816 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700817 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
818 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800819
820 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
821 mBaseUserRestrictions.put(userId, newRestrictions);
822 scheduleWriteUser(getUserInfoNoChecks(userId));
823 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700824 }
825
Fyodor Kupolov82402752015-10-28 14:54:51 -0700826 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700827
Makoto Onuki759a7632015-10-28 16:43:10 -0700828 mCachedEffectiveUserRestrictions.put(userId, effective);
829
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800830 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700831 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800832 debug("Applying user restrictions: userId=" + userId
833 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700834 }
835
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800836 if (mAppOpsService != null) { // We skip it until system-ready.
837 final long token = Binder.clearCallingIdentity();
838 try {
839 mAppOpsService.setUserRestrictions(effective, userId);
840 } catch (RemoteException e) {
841 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
842 } finally {
843 Binder.restoreCallingIdentity(token);
844 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700845 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700846
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800847 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700848
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800849 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700850 }
851
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800852 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800853 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800854 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
855 // actually, but we still need some kind of synchronization otherwise we might end up
856 // calling listeners out-of-order, thus "LR".
857
858 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
859 return;
860 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800861
862 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
863 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
864
865 mHandler.post(new Runnable() {
866 @Override
867 public void run() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800868 synchronized (mRestrictionsLock) {
869 UserRestrictionsUtils.applyUserRestrictionsLR(
870 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
871 }
872
Makoto Onukid45a4a22015-11-02 17:17:38 -0800873 final UserRestrictionsListener[] listeners;
874 synchronized (mUserRestrictionsListeners) {
875 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
876 mUserRestrictionsListeners.toArray(listeners);
877 }
878 for (int i = 0; i < listeners.length; i++) {
879 listeners[i].onUserRestrictionsChanged(userId,
880 newRestrictionsFinal, prevRestrictionsFinal);
881 }
882 }
883 });
884 }
885
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800886 // Package private for the inner class.
887 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700888 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700889 }
890
891 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800892 // Package private for the inner class.
893 void applyUserRestrictionsForAllUsersLR() {
894 if (DBG) {
895 debug("applyUserRestrictionsForAllUsersLR");
896 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700897 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700898 mCachedEffectiveUserRestrictions.clear();
899
Makoto Onuki068c54a2015-10-13 14:34:03 -0700900 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
901 // it on a handler.
902 final Runnable r = new Runnable() {
903 @Override
904 public void run() {
905 // Then get the list of running users.
906 final int[] runningUsers;
907 try {
908 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
909 } catch (RemoteException e) {
910 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
911 return;
912 }
913 // Then re-calculate the effective restrictions and apply, only for running users.
914 // It's okay if a new user has started after the getRunningUserIds() call,
915 // because we'll do the same thing (re-calculate the restrictions and apply)
916 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700917 synchronized (mRestrictionsLock) {
918 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800919 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700920 }
921 }
922 }
923 };
924 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700925 }
926
Amith Yamasani258848d2012-08-10 17:06:33 -0700927 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700928 * Check if we've hit the limit of how many users can be created.
929 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700930 private boolean isUserLimitReached() {
931 int count;
932 synchronized (mUsersLock) {
933 count = getAliveUsersExcludingGuestsCountLU();
934 }
935 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700936 }
937
938 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000939 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700940 checkManageUsersPermission("check if more managed profiles can be added.");
941 if (ActivityManager.isLowRamDeviceStatic()) {
942 return false;
943 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700944 if (!mContext.getPackageManager().hasSystemFeature(
945 PackageManager.FEATURE_MANAGED_USERS)) {
946 return false;
947 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100948 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000949 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
950 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
951 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100952 return false;
953 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700954 synchronized(mUsersLock) {
955 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100956 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700957 return false;
958 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000959 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
960 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -0700961 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000962 return usersCountAfterRemoving == 1
963 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700964 }
965 }
966
Fyodor Kupolov82402752015-10-28 14:54:51 -0700967 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700968 int aliveUserCount = 0;
969 final int totalUserCount = mUsers.size();
970 // Skip over users being removed
971 for (int i = 0; i < totalUserCount; i++) {
972 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700973 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700974 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700975 aliveUserCount++;
976 }
977 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700978 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700979 }
980
981 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700982 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700983 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700984 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700985 *
986 * @param message used as message if SecurityException is thrown
987 * @throws SecurityException if the caller is not system or root
988 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700989 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700990 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700991 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400992 && ActivityManager.checkComponentPermission(
993 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700994 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
995 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
996 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400997 }
998
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700999 private static void checkSystemOrRoot(String message) {
1000 final int uid = Binder.getCallingUid();
1001 if (uid != Process.SYSTEM_UID && uid != 0) {
1002 throw new SecurityException("Only system may call: " + message);
1003 }
1004 }
1005
Fyodor Kupolov82402752015-10-28 14:54:51 -07001006 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001007 try {
1008 File dir = new File(mUsersDir, Integer.toString(info.id));
1009 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001010 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001011 if (!dir.exists()) {
1012 dir.mkdir();
1013 FileUtils.setPermissions(
1014 dir.getPath(),
1015 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1016 -1, -1);
1017 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001018 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001019 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1020 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001021 info.iconPath = file.getAbsolutePath();
1022 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001023 try {
1024 os.close();
1025 } catch (IOException ioe) {
1026 // What the ... !
1027 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001028 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001029 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001030 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001031 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001032 }
1033
Amith Yamasani0b285492011-04-14 17:35:23 -07001034 /**
1035 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1036 * cache it elsewhere.
1037 * @return the array of user ids.
1038 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001039 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001040 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001041 return mUserIds;
1042 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001043 }
1044
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001045 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001046 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001047 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001048 return;
1049 }
1050 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001051 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001052 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001053 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001054 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001055 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001056 int type;
1057 while ((type = parser.next()) != XmlPullParser.START_TAG
1058 && type != XmlPullParser.END_DOCUMENT) {
1059 ;
1060 }
1061
1062 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001063 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001064 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001065 return;
1066 }
1067
Amith Yamasani2a003292012-08-14 18:25:45 -07001068 mNextSerialNumber = -1;
1069 if (parser.getName().equals(TAG_USERS)) {
1070 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1071 if (lastSerialNumber != null) {
1072 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1073 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001074 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1075 if (versionNumber != null) {
1076 mUserVersion = Integer.parseInt(versionNumber);
1077 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001078 }
1079
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001080 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1081
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001082 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301083 if (type == XmlPullParser.START_TAG) {
1084 final String name = parser.getName();
1085 if (name.equals(TAG_USER)) {
1086 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001087 UserInfo user = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001088
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301089 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001090 synchronized (mUsersLock) {
1091 mUsers.put(user.id, user);
1092 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1093 mNextSerialNumber = user.id + 1;
1094 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301095 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001096 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301097 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001098 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1099 && type != XmlPullParser.END_TAG) {
1100 if (type == XmlPullParser.START_TAG) {
1101 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001102 synchronized (mGuestRestrictions) {
1103 UserRestrictionsUtils
1104 .readRestrictions(parser, mGuestRestrictions);
1105 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001106 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1107 ) {
1108 UserRestrictionsUtils.readRestrictions(parser,
1109 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001110 }
1111 break;
1112 }
1113 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001114 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001115 }
1116 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001117 synchronized (mRestrictionsLock) {
1118 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1119 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001120 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001121 upgradeIfNecessaryLP();
1122 } catch (IOException | XmlPullParserException e) {
1123 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001124 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001125 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001126 }
1127 }
1128
Amith Yamasani6f34b412012-10-22 18:19:27 -07001129 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001130 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001131 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001132 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001133 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001134 int userVersion = mUserVersion;
1135 if (userVersion < 1) {
1136 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001137 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001138 if ("Primary".equals(user.name)) {
1139 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001140 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001141 }
1142 userVersion = 1;
1143 }
1144
Amith Yamasanibc9625052012-11-15 14:39:18 -08001145 if (userVersion < 2) {
1146 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001147 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001148 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1149 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001150 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001151 }
1152 userVersion = 2;
1153 }
1154
Amith Yamasani350962c2013-08-06 11:18:53 -07001155
Amith Yamasani5e486f52013-08-07 11:06:44 -07001156 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001157 userVersion = 4;
1158 }
1159
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001160 if (userVersion < 5) {
1161 initDefaultGuestRestrictions();
1162 userVersion = 5;
1163 }
1164
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001165 if (userVersion < 6) {
1166 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001167 synchronized (mUsersLock) {
1168 for (int i = 0; i < mUsers.size(); i++) {
1169 UserInfo user = mUsers.valueAt(i);
1170 // In non-split mode, only user 0 can have restricted profiles
1171 if (!splitSystemUser && user.isRestricted()
1172 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1173 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001174 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001175 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001176 }
1177 }
1178 userVersion = 6;
1179 }
1180
Amith Yamasani6f34b412012-10-22 18:19:27 -07001181 if (userVersion < USER_VERSION) {
1182 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1183 + USER_VERSION);
1184 } else {
1185 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001186
1187 if (originalVersion < mUserVersion) {
1188 writeUserListLP();
1189 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001190 }
1191 }
1192
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001193 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001194 int flags = UserInfo.FLAG_INITIALIZED;
1195 // In split system user mode, the admin and primary flags are assigned to the first human
1196 // user.
1197 if (!UserManager.isSplitSystemUser()) {
1198 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1199 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001200 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001201 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001202 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001203 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001204 synchronized (mUsersLock) {
1205 mUsers.put(system.id, system);
1206 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001207 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001208 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001209
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001210 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001211 synchronized (mRestrictionsLock) {
1212 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1213 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001214
Fyodor Kupolov82402752015-10-28 14:54:51 -07001215 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001216 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001217
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001218 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001219 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001220 }
1221
Makoto Onuki9e935a32015-11-06 14:24:24 -08001222 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001223 if (DBG) {
1224 debug("scheduleWriteUser");
1225 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001226 // No need to wrap it within a lock -- worst case, we'll just post the same message
1227 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001228 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1229 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1230 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1231 }
1232 }
1233
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001234 /*
1235 * Writes the user file in this format:
1236 *
1237 * <user flags="20039023" id="0">
1238 * <name>Primary</name>
1239 * </user>
1240 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001241 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001242 if (DBG) {
1243 debug("writeUserLP " + userInfo);
1244 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001245 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001246 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001247 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001248 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001249 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1250
1251 // XmlSerializer serializer = XmlUtils.serializerInstance();
1252 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001253 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001254 serializer.startDocument(null, true);
1255 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1256
1257 serializer.startTag(null, TAG_USER);
1258 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001259 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001260 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001261 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1262 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1263 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001264 if (userInfo.iconPath != null) {
1265 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1266 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001267 if (userInfo.partial) {
1268 serializer.attribute(null, ATTR_PARTIAL, "true");
1269 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001270 if (userInfo.guestToRemove) {
1271 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1272 }
Kenny Guy2a764942014-04-02 13:29:20 +01001273 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1274 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1275 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001276 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001277 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1278 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1279 Integer.toString(userInfo.restrictedProfileParentId));
1280 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001281 serializer.startTag(null, TAG_NAME);
1282 serializer.text(userInfo.name);
1283 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001284 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001285 UserRestrictionsUtils.writeRestrictions(serializer,
1286 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1287 UserRestrictionsUtils.writeRestrictions(serializer,
1288 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1289 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001290 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001291 serializer.endTag(null, TAG_USER);
1292
1293 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001294 userFile.finishWrite(fos);
1295 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001296 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001297 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001298 }
1299 }
1300
1301 /*
1302 * Writes the user list file in this format:
1303 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001304 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001305 * <user id="0"></user>
1306 * <user id="2"></user>
1307 * </users>
1308 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001309 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001310 if (DBG) {
1311 debug("writeUserList");
1312 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001313 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001314 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001315 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001316 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001317 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1318
1319 // XmlSerializer serializer = XmlUtils.serializerInstance();
1320 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001321 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001322 serializer.startDocument(null, true);
1323 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1324
1325 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001326 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001327 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001328
Adam Lesinskieddeb492014-09-08 17:50:03 -07001329 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001330 synchronized (mGuestRestrictions) {
1331 UserRestrictionsUtils
1332 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1333 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301334 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001335 synchronized (mRestrictionsLock) {
1336 UserRestrictionsUtils.writeRestrictions(serializer,
1337 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1338 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001339 int[] userIdsToWrite;
1340 synchronized (mUsersLock) {
1341 userIdsToWrite = new int[mUsers.size()];
1342 for (int i = 0; i < userIdsToWrite.length; i++) {
1343 UserInfo user = mUsers.valueAt(i);
1344 userIdsToWrite[i] = user.id;
1345 }
1346 }
1347 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001348 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001349 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001350 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001351 }
1352
1353 serializer.endTag(null, TAG_USERS);
1354
1355 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001356 userListFile.finishWrite(fos);
1357 } catch (Exception e) {
1358 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001359 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001360 }
1361 }
1362
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001363 private UserInfo readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001364 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001365 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001366 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001367 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001368 long creationTime = 0L;
1369 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001370 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001371 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001372 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001373 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001374 Bundle baseRestrictions = new Bundle();
1375 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001376
1377 FileInputStream fis = null;
1378 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001379 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001380 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001381 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001382 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001383 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001384 int type;
1385 while ((type = parser.next()) != XmlPullParser.START_TAG
1386 && type != XmlPullParser.END_DOCUMENT) {
1387 ;
1388 }
1389
1390 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001391 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001392 return null;
1393 }
1394
1395 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001396 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1397 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001398 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001399 return null;
1400 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001401 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1402 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001403 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001404 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1405 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001406 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1407 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001408 restrictedProfileParentId = readIntAttribute(parser,
1409 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001410 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1411 if ("true".equals(valueString)) {
1412 partial = true;
1413 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001414 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1415 if ("true".equals(valueString)) {
1416 guestToRemove = true;
1417 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001418
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001419 int outerDepth = parser.getDepth();
1420 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1421 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1422 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1423 continue;
1424 }
1425 String tag = parser.getName();
1426 if (TAG_NAME.equals(tag)) {
1427 type = parser.next();
1428 if (type == XmlPullParser.TEXT) {
1429 name = parser.getText();
1430 }
1431 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001432 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1433 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1434 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001435 }
1436 }
1437 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001438
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001439 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001440 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001441 userInfo.creationTime = creationTime;
1442 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001443 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001444 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001445 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001446 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001447 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001448 mBaseUserRestrictions.put(id, baseRestrictions);
1449 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001450 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001451 return userInfo;
1452
1453 } catch (IOException ioe) {
1454 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001455 } finally {
1456 if (fis != null) {
1457 try {
1458 fis.close();
1459 } catch (IOException e) {
1460 }
1461 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001462 }
1463 return null;
1464 }
1465
Amith Yamasani920ace02012-09-20 22:15:37 -07001466 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1467 String valueString = parser.getAttributeValue(null, attr);
1468 if (valueString == null) return defaultValue;
1469 try {
1470 return Integer.parseInt(valueString);
1471 } catch (NumberFormatException nfe) {
1472 return defaultValue;
1473 }
1474 }
1475
1476 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1477 String valueString = parser.getAttributeValue(null, attr);
1478 if (valueString == null) return defaultValue;
1479 try {
1480 return Long.parseLong(valueString);
1481 } catch (NumberFormatException nfe) {
1482 return defaultValue;
1483 }
1484 }
1485
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001486 private boolean isPackageInstalled(String pkg, int userId) {
1487 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1488 PackageManager.GET_UNINSTALLED_PACKAGES,
1489 userId);
1490 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1491 return false;
1492 }
1493 return true;
1494 }
1495
Amith Yamasanib82add22013-07-09 11:24:44 -07001496 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001497 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001498 * Does not do any permissions checking.
1499 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001500 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001501 synchronized (mPackagesLock) {
1502 File dir = Environment.getUserSystemDirectory(userId);
1503 String[] files = dir.list();
1504 if (files == null) return;
1505 for (String fileName : files) {
1506 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1507 File resFile = new File(dir, fileName);
1508 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001509 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001510 }
1511 }
1512 }
1513 }
1514 }
1515
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001516 /**
1517 * Removes the app restrictions file for a specific package and user id, if it exists.
1518 */
1519 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1520 synchronized (mPackagesLock) {
1521 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001522 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001523 if (resFile.exists()) {
1524 resFile.delete();
1525 }
1526 }
1527 }
1528
Kenny Guya52dc3e2014-02-11 15:33:14 +00001529 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001530 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001531 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001532 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001533 }
1534
Amith Yamasani258848d2012-08-10 17:06:33 -07001535 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001536 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001537 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001538 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001539 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001540
Jessica Hummelbe81c802014-04-22 15:49:22 +01001541 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001542 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001543 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1544 return null;
1545 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001546 if (ActivityManager.isLowRamDeviceStatic()) {
1547 return null;
1548 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001549 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001550 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001551 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001552 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001553 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001554 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001555 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001556 synchronized (mPackagesLock) {
1557 UserInfo parent = null;
1558 if (parentId != UserHandle.USER_NULL) {
1559 synchronized (mUsersLock) {
1560 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001561 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001562 if (parent == null) return null;
1563 }
1564 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1565 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1566 return null;
1567 }
1568 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1569 // If we're not adding a guest user or a managed profile and the limit has
1570 // been reached, cannot add a user.
1571 return null;
1572 }
1573 // If we're adding a guest and there already exists one, bail.
1574 if (isGuest && findCurrentGuestUser() != null) {
1575 return null;
1576 }
1577 // In legacy mode, restricted profile's parent can only be the owner user
1578 if (isRestricted && !UserManager.isSplitSystemUser()
1579 && (parentId != UserHandle.USER_SYSTEM)) {
1580 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1581 return null;
1582 }
1583 if (isRestricted && UserManager.isSplitSystemUser()) {
1584 if (parent == null) {
1585 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1586 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001587 return null;
1588 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001589 if (!parent.canHaveProfile()) {
1590 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1591 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001592 return null;
1593 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001594 }
1595 // In split system user mode, we assign the first human user the primary flag.
1596 // And if there is no device owner, we also assign the admin flag to primary user.
1597 if (UserManager.isSplitSystemUser()
1598 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1599 flags |= UserInfo.FLAG_PRIMARY;
1600 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1601 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1602 if (devicePolicyManager == null
Makoto Onukic8a5a552015-11-19 14:29:12 -08001603 || !devicePolicyManager.isDeviceManaged()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001604 flags |= UserInfo.FLAG_ADMIN;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001605 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001606 }
1607 userId = getNextAvailableId();
1608 userInfo = new UserInfo(userId, name, null, flags);
1609 userInfo.serialNumber = mNextSerialNumber++;
1610 long now = System.currentTimeMillis();
1611 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1612 userInfo.partial = true;
1613 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1614 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001615 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001616 }
1617 writeUserListLP();
1618 if (parent != null) {
1619 if (isManagedProfile) {
1620 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1621 parent.profileGroupId = parent.id;
1622 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001623 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001624 userInfo.profileGroupId = parent.profileGroupId;
1625 } else if (isRestricted) {
1626 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1627 parent.restrictedProfileParentId = parent.id;
1628 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001629 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001630 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001631 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001632 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001633 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001634 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1635 storage.createUserKey(userId, userInfo.serialNumber);
1636 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1637 final String volumeUuid = vol.getFsUuid();
1638 try {
1639 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1640 storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
1641 enforceSerialNumber(userDir, userInfo.serialNumber);
1642 } catch (IOException e) {
1643 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1644 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001645 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001646 mPm.createNewUser(userId);
1647 userInfo.partial = false;
1648 synchronized (mPackagesLock) {
1649 writeUserLP(userInfo);
1650 }
1651 updateUserIds();
1652 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001653 if (isGuest) {
1654 synchronized (mGuestRestrictions) {
1655 restrictions.putAll(mGuestRestrictions);
1656 }
1657 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001658 synchronized (mRestrictionsLock) {
1659 mBaseUserRestrictions.append(userId, restrictions);
1660 }
1661 mPm.newUserCreated(userId);
1662 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1663 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1664 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1665 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001666 } finally {
1667 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001668 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001669 return userInfo;
1670 }
1671
Amith Yamasani0b285492011-04-14 17:35:23 -07001672 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001673 * @hide
1674 */
1675 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1676 checkManageUsersPermission("setupRestrictedProfile");
1677 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1678 if (user == null) {
1679 return null;
1680 }
1681 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1682 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1683 // the putIntForUser() will fail.
1684 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1685 android.provider.Settings.Secure.LOCATION_MODE,
1686 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1687 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1688 return user;
1689 }
1690
1691 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001692 * Find the current guest user. If the Guest user is partial,
1693 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001694 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001695 private UserInfo findCurrentGuestUser() {
1696 synchronized (mUsersLock) {
1697 final int size = mUsers.size();
1698 for (int i = 0; i < size; i++) {
1699 final UserInfo user = mUsers.valueAt(i);
1700 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1701 return user;
1702 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001703 }
1704 }
1705 return null;
1706 }
1707
1708 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001709 * Mark this guest user for deletion to allow us to create another guest
1710 * and switch to that user before actually removing this guest.
1711 * @param userHandle the userid of the current guest
1712 * @return whether the user could be marked for deletion
1713 */
1714 public boolean markGuestForDeletion(int userHandle) {
1715 checkManageUsersPermission("Only the system can remove users");
1716 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1717 UserManager.DISALLOW_REMOVE_USER, false)) {
1718 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1719 return false;
1720 }
1721
1722 long ident = Binder.clearCallingIdentity();
1723 try {
1724 final UserInfo user;
1725 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001726 synchronized (mUsersLock) {
1727 user = mUsers.get(userHandle);
1728 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1729 return false;
1730 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001731 }
1732 if (!user.isGuest()) {
1733 return false;
1734 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001735 // We set this to a guest user that is to be removed. This is a temporary state
1736 // where we are allowed to add new Guest users, even if this one is still not
1737 // removed. This user will still show up in getUserInfo() calls.
1738 // If we don't get around to removing this Guest user, it will be purged on next
1739 // startup.
1740 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001741 // Mark it as disabled, so that it isn't returned any more when
1742 // profiles are queried.
1743 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001744 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001745 }
1746 } finally {
1747 Binder.restoreCallingIdentity(ident);
1748 }
1749 return true;
1750 }
1751
1752 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001753 * Removes a user and all data directories created for that user. This method should be called
1754 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001755 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001756 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001757 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001758 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001759 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1760 UserManager.DISALLOW_REMOVE_USER, false)) {
1761 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1762 return false;
1763 }
1764
Kenny Guyee58b4f2014-05-23 15:19:53 +01001765 long ident = Binder.clearCallingIdentity();
1766 try {
1767 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001768 int currentUser = ActivityManager.getCurrentUser();
1769 if (currentUser == userHandle) {
1770 Log.w(LOG_TAG, "Current user cannot be removed");
1771 return false;
1772 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001773 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001774 synchronized (mUsersLock) {
1775 user = mUsers.get(userHandle);
1776 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1777 return false;
1778 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001779
Fyodor Kupolov82402752015-10-28 14:54:51 -07001780 // We remember deleted user IDs to prevent them from being
1781 // reused during the current boot; they can still be reused
1782 // after a reboot.
1783 mRemovingUserIds.put(userHandle, true);
1784 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001785
Kenny Guyee58b4f2014-05-23 15:19:53 +01001786 try {
1787 mAppOpsService.removeUser(userHandle);
1788 } catch (RemoteException e) {
1789 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1790 }
1791 // Set this to a partially created user, so that the user will be purged
1792 // on next startup, in case the runtime stops now before stopping and
1793 // removing the user completely.
1794 user.partial = true;
1795 // Mark it as disabled, so that it isn't returned any more when
1796 // profiles are queried.
1797 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001798 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001799 }
1800
1801 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1802 && user.isManagedProfile()) {
1803 // Send broadcast to notify system that the user removed was a
1804 // managed user.
1805 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1806 }
1807
1808 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1809 int res;
1810 try {
1811 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1812 new IStopUserCallback.Stub() {
1813 @Override
1814 public void userStopped(int userId) {
1815 finishRemoveUser(userId);
1816 }
1817 @Override
1818 public void userStopAborted(int userId) {
1819 }
1820 });
1821 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001822 return false;
1823 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001824 return res == ActivityManager.USER_OP_SUCCESS;
1825 } finally {
1826 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001827 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001828 }
1829
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001830 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001831 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001832 // Let other services shutdown any activity and clean up their state before completely
1833 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001834 long ident = Binder.clearCallingIdentity();
1835 try {
1836 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1837 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001838 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1839 android.Manifest.permission.MANAGE_USERS,
1840
1841 new BroadcastReceiver() {
1842 @Override
1843 public void onReceive(Context context, Intent intent) {
1844 if (DBG) {
1845 Slog.i(LOG_TAG,
1846 "USER_REMOVED broadcast sent, cleaning up user data "
1847 + userHandle);
1848 }
1849 new Thread() {
1850 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001851 // Clean up any ActivityManager state
1852 LocalServices.getService(ActivityManagerInternal.class)
1853 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001854 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001855 }
1856 }.start();
1857 }
1858 },
1859
1860 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001861 } finally {
1862 Binder.restoreCallingIdentity(ident);
1863 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001864 }
1865
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001866 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001867 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001868 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001869 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001870
1871 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001872 synchronized (mUsersLock) {
1873 mUsers.remove(userHandle);
1874 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001875 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001876 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001877 userFile.delete();
1878 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001879 synchronized (mPackagesLock) {
1880 writeUserListLP();
1881 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001882 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001883 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1884 }
1885
Amith Yamasani61f57372012-08-31 12:12:28 -07001886 private void removeDirectoryRecursive(File parent) {
1887 if (parent.isDirectory()) {
1888 String[] files = parent.list();
1889 for (String filename : files) {
1890 File child = new File(parent, filename);
1891 removeDirectoryRecursive(child);
1892 }
1893 }
1894 parent.delete();
1895 }
1896
Kenny Guyf8d3a232014-05-15 16:09:52 +01001897 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001898 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001899 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1900 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001901 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1902 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001903 }
1904
Amith Yamasani2a003292012-08-14 18:25:45 -07001905 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001906 public Bundle getApplicationRestrictions(String packageName) {
1907 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1908 }
1909
1910 @Override
1911 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001912 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001913 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001914 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001915 }
1916 synchronized (mPackagesLock) {
1917 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001918 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001919 }
1920 }
1921
1922 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001923 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001924 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001925 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001926 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001927 if (restrictions == null || restrictions.isEmpty()) {
1928 cleanAppRestrictionsForPackage(packageName, userId);
1929 } else {
1930 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001931 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001932 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001933 }
Robin Lee66e5d962014-04-09 16:44:21 +01001934
Kenny Guyd21b2182014-07-17 16:38:55 +01001935 if (isPackageInstalled(packageName, userId)) {
1936 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1937 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1938 changeIntent.setPackage(packageName);
1939 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1940 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1941 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001942 }
1943
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001944 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001945 mHandler.post(new Runnable() {
1946 @Override
1947 public void run() {
1948 List<ApplicationInfo> apps =
1949 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1950 userHandle).getList();
1951 final long ident = Binder.clearCallingIdentity();
1952 try {
1953 for (ApplicationInfo appInfo : apps) {
1954 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001955 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1956 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001957 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001958 userHandle);
1959 }
1960 }
1961 } finally {
1962 Binder.restoreCallingIdentity(ident);
1963 }
1964 }
1965 });
1966 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001967 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001968 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001969 try {
1970 return mContext.getPackageManager().getApplicationInfo(packageName,
1971 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1972 } catch (NameNotFoundException nnfe) {
1973 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001974 } finally {
1975 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001976 }
1977 }
1978
Fyodor Kupolov82402752015-10-28 14:54:51 -07001979 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001980 AtomicFile restrictionsFile =
1981 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1982 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001983 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001984 }
1985
1986 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001987 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001988 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001989 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001990 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001991 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001992 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001993
1994 FileInputStream fis = null;
1995 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001996 fis = restrictionsFile.openRead();
1997 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001998 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001999 XmlUtils.nextElement(parser);
2000 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002001 Slog.e(LOG_TAG, "Unable to read restrictions file "
2002 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002003 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002004 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002005 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2006 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002007 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002008 } catch (IOException|XmlPullParserException e) {
2009 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002010 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002011 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002012 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002013 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002014 }
2015
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002016 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2017 XmlPullParser parser) throws XmlPullParserException, IOException {
2018 int type = parser.getEventType();
2019 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2020 String key = parser.getAttributeValue(null, ATTR_KEY);
2021 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2022 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2023 if (multiple != null) {
2024 values.clear();
2025 int count = Integer.parseInt(multiple);
2026 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2027 if (type == XmlPullParser.START_TAG
2028 && parser.getName().equals(TAG_VALUE)) {
2029 values.add(parser.nextText().trim());
2030 count--;
2031 }
2032 }
2033 String [] valueStrings = new String[values.size()];
2034 values.toArray(valueStrings);
2035 restrictions.putStringArray(key, valueStrings);
2036 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2037 restrictions.putBundle(key, readBundleEntry(parser, values));
2038 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2039 final int outerDepth = parser.getDepth();
2040 ArrayList<Bundle> bundleList = new ArrayList<>();
2041 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2042 Bundle childBundle = readBundleEntry(parser, values);
2043 bundleList.add(childBundle);
2044 }
2045 restrictions.putParcelableArray(key,
2046 bundleList.toArray(new Bundle[bundleList.size()]));
2047 } else {
2048 String value = parser.nextText().trim();
2049 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2050 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2051 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2052 restrictions.putInt(key, Integer.parseInt(value));
2053 } else {
2054 restrictions.putString(key, value);
2055 }
2056 }
2057 }
2058 }
2059
2060 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2061 throws IOException, XmlPullParserException {
2062 Bundle childBundle = new Bundle();
2063 final int outerDepth = parser.getDepth();
2064 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2065 readEntry(childBundle, values, parser);
2066 }
2067 return childBundle;
2068 }
2069
Fyodor Kupolov82402752015-10-28 14:54:51 -07002070 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002071 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002072 AtomicFile restrictionsFile = new AtomicFile(
2073 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002074 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002075 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002076 }
2077
2078 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002079 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002080 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002081 try {
2082 fos = restrictionsFile.startWrite();
2083 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2084
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002085 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002086 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002087 serializer.startDocument(null, true);
2088 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2089
2090 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002091 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002092 serializer.endTag(null, TAG_RESTRICTIONS);
2093
2094 serializer.endDocument();
2095 restrictionsFile.finishWrite(fos);
2096 } catch (Exception e) {
2097 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002098 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2099 }
2100 }
2101
2102 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2103 throws IOException {
2104 for (String key : restrictions.keySet()) {
2105 Object value = restrictions.get(key);
2106 serializer.startTag(null, TAG_ENTRY);
2107 serializer.attribute(null, ATTR_KEY, key);
2108
2109 if (value instanceof Boolean) {
2110 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2111 serializer.text(value.toString());
2112 } else if (value instanceof Integer) {
2113 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2114 serializer.text(value.toString());
2115 } else if (value == null || value instanceof String) {
2116 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2117 serializer.text(value != null ? (String) value : "");
2118 } else if (value instanceof Bundle) {
2119 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2120 writeBundle((Bundle) value, serializer);
2121 } else if (value instanceof Parcelable[]) {
2122 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2123 Parcelable[] array = (Parcelable[]) value;
2124 for (Parcelable parcelable : array) {
2125 if (!(parcelable instanceof Bundle)) {
2126 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2127 }
2128 serializer.startTag(null, TAG_ENTRY);
2129 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2130 writeBundle((Bundle) parcelable, serializer);
2131 serializer.endTag(null, TAG_ENTRY);
2132 }
2133 } else {
2134 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2135 String[] values = (String[]) value;
2136 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2137 for (String choice : values) {
2138 serializer.startTag(null, TAG_VALUE);
2139 serializer.text(choice != null ? choice : "");
2140 serializer.endTag(null, TAG_VALUE);
2141 }
2142 }
2143 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002144 }
2145 }
2146
2147 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002148 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002149 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002150 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002151 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002152 }
2153 }
2154
2155 @Override
2156 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002157 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002158 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002159 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002160 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002161 }
2162 // Not found
2163 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002164 }
2165 }
2166
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002167 @Override
2168 public long getUserCreationTime(int userHandle) {
2169 int callingUserId = UserHandle.getCallingUserId();
2170 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002171 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002172 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002173 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002174 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002175 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002176 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002177 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002178 }
2179 }
2180 }
2181 if (userInfo == null) {
2182 throw new SecurityException("userHandle can only be the calling user or a managed "
2183 + "profile associated with this user");
2184 }
2185 return userInfo.creationTime;
2186 }
2187
Amith Yamasani0b285492011-04-14 17:35:23 -07002188 /**
2189 * Caches the list of user ids in an array, adjusting the array size when necessary.
2190 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002191 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002192 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002193 synchronized (mUsersLock) {
2194 final int userSize = mUsers.size();
2195 for (int i = 0; i < userSize; i++) {
2196 if (!mUsers.valueAt(i).partial) {
2197 num++;
2198 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002199 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002200 final int[] newUsers = new int[num];
2201 int n = 0;
2202 for (int i = 0; i < userSize; i++) {
2203 if (!mUsers.valueAt(i).partial) {
2204 newUsers[n++] = mUsers.keyAt(i);
2205 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002206 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002207 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002208 }
2209 }
2210
2211 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002212 * Called right before a user starts. This will not be called for the system user.
2213 */
2214 public void onBeforeStartUser(int userId) {
2215 synchronized (mRestrictionsLock) {
2216 applyUserRestrictionsLR(userId);
2217 }
2218 }
2219
2220 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002221 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002222 * @param userId the user that was just foregrounded
2223 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002224 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002225 UserInfo user = getUserInfoNoChecks(userId);
2226 if (user == null || user.partial) {
2227 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2228 return;
2229 }
2230 long now = System.currentTimeMillis();
2231 if (now > EPOCH_PLUS_30_YEARS) {
2232 user.lastLoggedInTime = now;
2233 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002234 }
2235 }
2236
2237 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002238 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002239 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2240 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002241 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002242 private int getNextAvailableId() {
2243 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002244 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002245 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002246 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002247 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002248 }
2249 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002250 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002251 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002252 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002253 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002254
Amith Yamasanifc95e702013-09-26 13:20:17 -07002255 private String packageToRestrictionsFileName(String packageName) {
2256 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2257 }
2258
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002259 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002260 * Enforce that serial number stored in user directory inode matches the
2261 * given expected value. Gracefully sets the serial number if currently
2262 * undefined.
2263 *
2264 * @throws IOException when problem extracting serial number, or serial
2265 * number is mismatched.
2266 */
2267 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2268 final int foundSerial = getSerialNumber(file);
2269 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2270
2271 if (foundSerial == -1) {
2272 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2273 try {
2274 setSerialNumber(file, serialNumber);
2275 } catch (IOException e) {
2276 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2277 }
2278
2279 } else if (foundSerial != serialNumber) {
2280 throw new IOException("Found serial number " + foundSerial
2281 + " doesn't match expected " + serialNumber);
2282 }
2283 }
2284
2285 /**
2286 * Set serial number stored in user directory inode.
2287 *
2288 * @throws IOException if serial number was already set
2289 */
2290 private static void setSerialNumber(File file, int serialNumber)
2291 throws IOException {
2292 try {
2293 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2294 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2295 } catch (ErrnoException e) {
2296 throw e.rethrowAsIOException();
2297 }
2298 }
2299
2300 /**
2301 * Return serial number stored in user directory inode.
2302 *
2303 * @return parsed serial number, or -1 if not set
2304 */
2305 private static int getSerialNumber(File file) throws IOException {
2306 try {
2307 final byte[] buf = new byte[256];
2308 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2309 final String serial = new String(buf, 0, len);
2310 try {
2311 return Integer.parseInt(serial);
2312 } catch (NumberFormatException e) {
2313 throw new IOException("Bad serial number: " + serial);
2314 }
2315 } catch (ErrnoException e) {
2316 if (e.errno == OsConstants.ENODATA) {
2317 return -1;
2318 } else {
2319 throw e.rethrowAsIOException();
2320 }
2321 }
2322 }
2323
Amith Yamasani920ace02012-09-20 22:15:37 -07002324 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002325 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2326 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2327 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2328 }
2329
2330 int onShellCommand(Shell shell, String cmd) {
2331 if (cmd == null) {
2332 return shell.handleDefaultCommands(cmd);
2333 }
2334
2335 final PrintWriter pw = shell.getOutPrintWriter();
2336 try {
2337 switch(cmd) {
2338 case "list":
2339 return runList(pw);
2340 }
2341 } catch (RemoteException e) {
2342 pw.println("Remote exception: " + e);
2343 }
2344 return -1;
2345 }
2346
2347 private int runList(PrintWriter pw) throws RemoteException {
2348 final IActivityManager am = ActivityManagerNative.getDefault();
2349 final List<UserInfo> users = getUsers(false);
2350 if (users == null) {
2351 pw.println("Error: couldn't get users");
2352 return 1;
2353 } else {
2354 pw.println("Users:");
2355 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002356 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002357 pw.println("\t" + users.get(i).toString() + running);
2358 }
2359 return 0;
2360 }
2361 }
2362
2363 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002364 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2365 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2366 != PackageManager.PERMISSION_GRANTED) {
2367 pw.println("Permission Denial: can't dump UserManager from from pid="
2368 + Binder.getCallingPid()
2369 + ", uid=" + Binder.getCallingUid()
2370 + " without permission "
2371 + android.Manifest.permission.DUMP);
2372 return;
2373 }
2374
2375 long now = System.currentTimeMillis();
2376 StringBuilder sb = new StringBuilder();
2377 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002378 synchronized (mUsersLock) {
2379 pw.println("Users:");
2380 for (int i = 0; i < mUsers.size(); i++) {
2381 UserInfo user = mUsers.valueAt(i);
2382 if (user == null) {
2383 continue;
2384 }
2385 pw.print(" "); pw.print(user);
2386 pw.print(" serialNo="); pw.print(user.serialNumber);
2387 if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2388 pw.print(" <removing> ");
2389 }
2390 if (user.partial) {
2391 pw.print(" <partial>");
2392 }
2393 pw.println();
2394 pw.print(" Created: ");
2395 if (user.creationTime == 0) {
2396 pw.println("<unknown>");
2397 } else {
2398 sb.setLength(0);
2399 TimeUtils.formatDuration(now - user.creationTime, sb);
2400 sb.append(" ago");
2401 pw.println(sb);
2402 }
2403 pw.print(" Last logged in: ");
2404 if (user.lastLoggedInTime == 0) {
2405 pw.println("<unknown>");
2406 } else {
2407 sb.setLength(0);
2408 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2409 sb.append(" ago");
2410 pw.println(sb);
2411 }
2412 pw.println(" Restrictions:");
2413 synchronized (mRestrictionsLock) {
2414 UserRestrictionsUtils.dumpRestrictions(
2415 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002416 pw.println(" Device policy local restrictions:");
2417 UserRestrictionsUtils.dumpRestrictions(
2418 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002419 pw.println(" Effective restrictions:");
2420 UserRestrictionsUtils.dumpRestrictions(
2421 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2422 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002423 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002424 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002425 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002426 pw.println(" Device policy global restrictions:");
2427 synchronized (mRestrictionsLock) {
2428 UserRestrictionsUtils
2429 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2430 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002431 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002432 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002433 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002434 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002435 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002436 }
2437 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002438
2439 final class MainHandler extends Handler {
2440
2441 @Override
2442 public void handleMessage(Message msg) {
2443 switch (msg.what) {
2444 case WRITE_USER_MSG:
2445 removeMessages(WRITE_USER_MSG, msg.obj);
2446 synchronized (mPackagesLock) {
2447 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002448 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002449 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002450 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002451 }
2452 }
2453 }
2454 }
2455 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002456
2457 /**
2458 * @param userId
2459 * @return whether the user has been initialized yet
2460 */
2461 boolean isInitialized(int userId) {
2462 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2463 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002464
2465 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002466 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002467 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2468 @Nullable Bundle globalRestrictions) {
2469 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2470 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002471 }
2472
2473 @Override
2474 public Bundle getBaseUserRestrictions(int userId) {
2475 synchronized (mRestrictionsLock) {
2476 return mBaseUserRestrictions.get(userId);
2477 }
2478 }
2479
2480 @Override
2481 public void setBaseUserRestrictionsByDpmsForMigration(
2482 int userId, Bundle baseRestrictions) {
2483 synchronized (mRestrictionsLock) {
2484 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002485 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002486 }
2487
Fyodor Kupolov82402752015-10-28 14:54:51 -07002488 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002489 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002490 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002491 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002492 } else {
2493 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2494 }
2495 }
2496 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002497
2498 @Override
2499 public boolean getUserRestriction(int userId, String key) {
2500 return getUserRestrictions(userId).getBoolean(key);
2501 }
2502
2503 @Override
2504 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2505 synchronized (mUserRestrictionsListeners) {
2506 mUserRestrictionsListeners.add(listener);
2507 }
2508 }
2509
2510 @Override
2511 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2512 synchronized (mUserRestrictionsListeners) {
2513 mUserRestrictionsListeners.remove(listener);
2514 }
2515 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002516 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002517
2518 private class Shell extends ShellCommand {
2519 @Override
2520 public int onCommand(String cmd) {
2521 return onShellCommand(this, cmd);
2522 }
2523
2524 @Override
2525 public void onHelp() {
2526 final PrintWriter pw = getOutPrintWriter();
2527 pw.println("User manager (user) commands:");
2528 pw.println(" help");
2529 pw.println(" Print this help text.");
2530 pw.println("");
2531 pw.println(" list");
2532 pw.println(" Prints all users on the system.");
2533 }
2534 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002535
2536 private static void debug(String message) {
2537 Log.d(LOG_TAG, message +
2538 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2539 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002540}