blob: 3a1d2de0d37c9cea9f218f2cb0fb3255a064c2ab [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;
Makoto Onuki068c54a2015-10-13 14:34:03 -070028import android.app.admin.DevicePolicyManagerInternal;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070029import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070030import android.content.Context;
31import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070032import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070033import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080034import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070035import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070036import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080038import android.os.Bundle;
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;
Clara Bayarrif05b9d02015-10-23 13:25:19 +010051import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070052import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070053import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070054import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080055import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010056import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070057import android.os.storage.VolumeInfo;
58import android.system.ErrnoException;
59import android.system.Os;
60import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070061import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070062import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import android.util.Slog;
64import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080065import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070066import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import android.util.Xml;
68
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070070import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040071import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080072import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070073import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070074import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070075import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080076
77import org.xmlpull.v1.XmlPullParser;
78import org.xmlpull.v1.XmlPullParserException;
79import org.xmlpull.v1.XmlSerializer;
80
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import java.io.BufferedOutputStream;
82import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070083import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070085import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import java.io.FileOutputStream;
87import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070088import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010089import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070090import java.util.ArrayList;
91import java.util.List;
92
Fyodor Kupolov262f9952015-03-23 18:55:11 -070093import libcore.io.IoUtils;
94
Makoto Onuki068c54a2015-10-13 14:34:03 -070095/**
96 * Service for {@link UserManager}.
97 *
98 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -070099 * <ul>
100 * <li> Methods suffixed with "LILP" should be called within {@link #mInstallLock} and
101 * {@link #mPackagesLock} locks obtained in the respective order.
102 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
103 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
104 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700105 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700106public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700107 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki068c54a2015-10-13 14:34:03 -0700108 private static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700109
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700112 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700114 private static final String ATTR_CREATION_TIME = "created";
115 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700116 private static final String ATTR_SERIAL_NO = "serialNumber";
117 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700118 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700119 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700120 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100121 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700122 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530123 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800126 private static final String TAG_RESTRICTIONS = "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;
167 private final Object mInstallLock;
168 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700169 // Short-term lock for internal state, when interaction/sync with PM is not required
170 private final Object mUsersLock = new Object();
171 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700172
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800173 private final Handler mHandler;
174
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700175 private final File mUsersDir;
176 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700177
Fyodor Kupolov82402752015-10-28 14:54:51 -0700178 @GuardedBy("mUsersLock")
179 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700180
181 /**
182 * User restrictions set via UserManager. This doesn't include restrictions set by
183 * device owner / profile owners.
184 *
185 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
186 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
187 * maybe shared between {@link #mBaseUserRestrictions} and
188 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
189 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700190 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700191 */
192 @GuardedBy("mRestrictionsLock")
193 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
194
195 /**
196 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
197 * with device / profile owner restrictions. We'll initialize it lazily; use
198 * {@link #getEffectiveUserRestrictions} to access it.
199 *
200 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
201 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
202 * maybe shared between {@link #mBaseUserRestrictions} and
203 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
204 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700205 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700206 */
207 @GuardedBy("mRestrictionsLock")
208 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
209
Makoto Onuki4f160732015-10-27 17:15:38 -0700210 /**
Fyodor Kupolov82402752015-10-28 14:54:51 -0700211 * User restrictions that have already been applied in {@link #applyUserRestrictionsLR}. We
Makoto Onuki4f160732015-10-27 17:15:38 -0700212 * use it to detect restrictions that have changed since the last
Fyodor Kupolov82402752015-10-28 14:54:51 -0700213 * {@link #applyUserRestrictionsLR} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700214 */
215 @GuardedBy("mRestrictionsLock")
216 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
217
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530218 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800219
220 /**
221 * Set of user IDs being actively removed. Removed IDs linger in this set
222 * for several seconds to work around a VFS caching issue.
223 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700224 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800225 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700226
Fyodor Kupolov82402752015-10-28 14:54:51 -0700227 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700228 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700229 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700230 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700231
Jason Monk62062992014-05-06 09:55:28 -0400232 private IAppOpsService mAppOpsService;
233
Makoto Onuki068c54a2015-10-13 14:34:03 -0700234 private final LocalService mLocalService;
235
Makoto Onukid45a4a22015-11-02 17:17:38 -0800236 @GuardedBy("mUserRestrictionsListeners")
237 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
238 new ArrayList<>();
239
Amith Yamasani258848d2012-08-10 17:06:33 -0700240 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700241
Dianne Hackborn4428e172012-08-24 17:43:05 -0700242 public static UserManagerService getInstance() {
243 synchronized (UserManagerService.class) {
244 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700245 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700246 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700247
248 /**
249 * Available for testing purposes.
250 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700251 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700252 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700253 }
254
Dianne Hackborn4428e172012-08-24 17:43:05 -0700255 /**
256 * Called by package manager to create the service. This is closely
257 * associated with the package manager, and the given lock is the
258 * package manager's own lock.
259 */
260 UserManagerService(Context context, PackageManagerService pm,
261 Object installLock, Object packagesLock) {
262 this(context, pm, installLock, packagesLock,
263 Environment.getDataDirectory(),
264 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700265 }
266
Dianne Hackborn4428e172012-08-24 17:43:05 -0700267 /**
268 * Available for testing purposes.
269 */
270 private UserManagerService(Context context, PackageManagerService pm,
271 Object installLock, Object packagesLock,
272 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700273 mContext = context;
274 mPm = pm;
275 mInstallLock = installLock;
276 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800277 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700278 synchronized (mInstallLock) {
279 synchronized (mPackagesLock) {
280 mUsersDir = new File(dataDir, USER_INFO_DIR);
281 mUsersDir.mkdirs();
282 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700283 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700284 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700285 FileUtils.setPermissions(mUsersDir.toString(),
286 FileUtils.S_IRWXU|FileUtils.S_IRWXG
287 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
288 -1, -1);
289 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800290 initDefaultGuestRestrictions();
Fyodor Kupolov82402752015-10-28 14:54:51 -0700291 readUserListLILP();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700292 sInstance = this;
293 }
294 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700295 mLocalService = new LocalService();
296 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700297 }
298
299 void systemReady() {
300 synchronized (mInstallLock) {
301 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700302 synchronized (mUsersLock) {
303 // Prune out any partially created/partially removed users.
304 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
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);
310 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700311 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700312 final int partialsSize = partials.size();
313 for (int i = 0; i < partialsSize; i++) {
314 UserInfo ui = partials.get(i);
315 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
316 + " (name=" + ui.name + ")");
317 removeUserStateLILP(ui.id);
318 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700319 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700320 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700321 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700322 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400323 mAppOpsService = IAppOpsService.Stub.asInterface(
324 ServiceManager.getService(Context.APP_OPS_SERVICE));
325 for (int i = 0; i < mUserIds.length; ++i) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700326 final int userId = mUserIds[i];
Jason Monk62062992014-05-06 09:55:28 -0400327 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700328 mAppOpsService.setUserRestrictions(getEffectiveUserRestrictions(userId), userId);
Jason Monk62062992014-05-06 09:55:28 -0400329 } catch (RemoteException e) {
330 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
331 }
332 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700333 }
334
335 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700336 public UserInfo getPrimaryUser() {
337 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700338 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700339 final int userSize = mUsers.size();
340 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700341 UserInfo ui = mUsers.valueAt(i);
342 if (ui.isPrimary()) {
343 return ui;
344 }
345 }
346 }
347 return null;
348 }
349
350 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700351 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700352 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700353 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700354 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700355 final int userSize = mUsers.size();
356 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700357 UserInfo ui = mUsers.valueAt(i);
358 if (ui.partial) {
359 continue;
360 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800361 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700362 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700363 }
Amith Yamasani13593602012-03-22 16:16:17 -0700364 }
365 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700366 }
Amith Yamasani13593602012-03-22 16:16:17 -0700367 }
368
Amith Yamasani258848d2012-08-10 17:06:33 -0700369 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100370 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800371 if (userId != UserHandle.getCallingUserId()) {
372 checkManageUsersPermission("getting profiles related to user " + userId);
373 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700374 final long ident = Binder.clearCallingIdentity();
375 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700376 synchronized (mUsersLock) {
377 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100378 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700379 } finally {
380 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000381 }
382 }
383
Amith Yamasanibe465322014-04-24 13:45:17 -0700384 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700385 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
386 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700387 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700388 if (user == null) {
389 // Probably a dying user
390 return users;
391 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700392 final int userSize = mUsers.size();
393 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700394 UserInfo profile = mUsers.valueAt(i);
395 if (!isProfileOf(user, profile)) {
396 continue;
397 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100398 if (enabledOnly && !profile.isEnabled()) {
399 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700400 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700401 if (mRemovingUserIds.get(profile.id)) {
402 continue;
403 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700404 users.add(profile);
405 }
406 return users;
407 }
408
Jessica Hummelbe81c802014-04-22 15:49:22 +0100409 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700410 public int getCredentialOwnerProfile(int userHandle) {
411 checkManageUsersPermission("get the credential owner");
Clara Bayarri965da392015-10-28 17:53:53 +0000412 if (!mContext.getSystemService(StorageManager.class).isPerUserEncryptionEnabled()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700413 synchronized (mUsersLock) {
414 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700415 if (profileParent != null) {
416 return profileParent.id;
417 }
418 }
419 }
420
421 return userHandle;
422 }
423
424 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700425 public boolean isSameProfileGroup(int userId, int otherUserId) {
426 if (userId == otherUserId) return true;
427 checkManageUsersPermission("check if in the same profile group");
428 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700429 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700430 }
431 }
432
Fyodor Kupolov82402752015-10-28 14:54:51 -0700433 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
434 synchronized (mUsersLock) {
435 UserInfo userInfo = getUserInfoLU(userId);
436 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
437 return false;
438 }
439 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
440 if (otherUserInfo == null
441 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
442 return false;
443 }
444 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700445 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700446 }
447
448 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100449 public UserInfo getProfileParent(int userHandle) {
450 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700451 synchronized (mUsersLock) {
452 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700453 }
454 }
455
Fyodor Kupolov82402752015-10-28 14:54:51 -0700456 private UserInfo getProfileParentLU(int userHandle) {
457 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700458 if (profile == null) {
459 return null;
460 }
461 int parentUserId = profile.profileGroupId;
462 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
463 return null;
464 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700465 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100466 }
467 }
468
Fyodor Kupolov82402752015-10-28 14:54:51 -0700469 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100470 return user.id == profile.id ||
471 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
472 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000473 }
474
475 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100476 public void setUserEnabled(int userId) {
477 checkManageUsersPermission("enable user");
478 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700479 UserInfo info;
480 synchronized (mUsersLock) {
481 info = getUserInfoLU(userId);
482 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100483 if (info != null && !info.isEnabled()) {
484 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700485 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100486 }
487 }
488 }
489
490 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700491 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700492 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700493 synchronized (mUsersLock) {
494 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700495 }
496 }
497
Amith Yamasani71e6c692013-03-24 17:39:28 -0700498 @Override
499 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700500 synchronized (mUsersLock) {
501 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700502 }
503 }
504
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700505 @Override
506 public boolean canHaveRestrictedProfile(int userId) {
507 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700508 synchronized (mUsersLock) {
509 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700510 if (userInfo == null || !userInfo.canHaveProfile()) {
511 return false;
512 }
513 if (!userInfo.isAdmin()) {
514 return false;
515 }
516 }
517 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
518 Context.DEVICE_POLICY_SERVICE);
519 // restricted profile can be created if there is no DO set and the admin user has no PO
520 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
521 }
522
Amith Yamasani195263742012-08-21 15:40:12 -0700523 /*
524 * Should be locked on mUsers before calling this.
525 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700526 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700527 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700528 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800529 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700530 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
531 return null;
532 }
533 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700534 }
535
Fyodor Kupolov82402752015-10-28 14:54:51 -0700536 /**
537 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
538 * <p>No permissions checking or any addition checks are made</p>
539 */
540 private UserInfo getUserInfoNoChecks(int userId) {
541 synchronized (mUsersLock) {
542 return mUsers.get(userId);
543 }
544 }
545
Amith Yamasani236b2b52015-08-18 14:32:14 -0700546 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700547 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700548 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700549 }
550
Amith Yamasani258848d2012-08-10 17:06:33 -0700551 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700552 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700553 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700554 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700555 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700556 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700557 if (info == null || info.partial) {
558 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
559 return;
560 }
Amith Yamasani13593602012-03-22 16:16:17 -0700561 if (name != null && !name.equals(info.name)) {
562 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700563 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700564 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700565 }
566 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700567 if (changed) {
568 sendUserInfoChangedBroadcast(userId);
569 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700570 }
571
Amith Yamasani258848d2012-08-10 17:06:33 -0700572 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700573 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700574 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400575 long ident = Binder.clearCallingIdentity();
576 try {
577 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700578 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400579 if (info == null || info.partial) {
580 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
581 return;
582 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700583 writeBitmapLP(info, bitmap);
584 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700585 }
Jason Monk9a944532014-07-08 09:31:21 -0400586 sendUserInfoChangedBroadcast(userId);
587 } finally {
588 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700589 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700590 }
591
592 private void sendUserInfoChangedBroadcast(int userId) {
593 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
594 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
595 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700596 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700597 }
598
Amith Yamasani258848d2012-08-10 17:06:33 -0700599 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100600 public ParcelFileDescriptor getUserIcon(int userId) {
601 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700602 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700603 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700604 if (info == null || info.partial) {
605 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
606 return null;
607 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700608 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100609 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
610 || callingGroupId != info.profileGroupId) {
611 checkManageUsersPermission("get the icon of a user who is not related");
612 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700613 if (info.iconPath == null) {
614 return null;
615 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100616 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700617 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100618
619 try {
620 return ParcelFileDescriptor.open(
621 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
622 } catch (FileNotFoundException e) {
623 Log.e(LOG_TAG, "Couldn't find icon file", e);
624 }
625 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700626 }
627
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700628 public void makeInitialized(int userId) {
629 checkManageUsersPermission("makeInitialized");
630 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700631 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700632 if (info == null || info.partial) {
633 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700634 // TODO Check if we should return here instead of a null check below
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700635 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700636 if (info != null && (info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700637 info.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -0800638 scheduleWriteUser(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700639 }
640 }
641 }
642
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700643 /**
644 * If default guest restrictions haven't been initialized yet, add the basic
645 * restrictions.
646 */
647 private void initDefaultGuestRestrictions() {
648 if (mGuestRestrictions.isEmpty()) {
649 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800650 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700651 }
652 }
653
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800654 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530655 public Bundle getDefaultGuestRestrictions() {
656 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700657 // TODO Switch to mGuestRestrictions for locking
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530658 synchronized (mPackagesLock) {
659 return new Bundle(mGuestRestrictions);
660 }
661 }
662
663 @Override
664 public void setDefaultGuestRestrictions(Bundle restrictions) {
665 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700666 synchronized (mInstallLock) {
667 synchronized (mPackagesLock) {
668 mGuestRestrictions.clear();
669 mGuestRestrictions.putAll(restrictions);
670 writeUserListLILP();
671 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530672 }
673 }
674
Makoto Onuki068c54a2015-10-13 14:34:03 -0700675 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700676 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700677 final DevicePolicyManagerInternal dpmi =
678 LocalServices.getService(DevicePolicyManagerInternal.class);
679 final Bundle systemRestrictions = mBaseUserRestrictions.get(userId);
680
681 final Bundle effective;
682 if (dpmi == null) {
683 // TODO Make sure it's because DPMS is disabled and not because we called it too early.
684 effective = systemRestrictions;
685 } else {
686 effective = dpmi.getComposedUserRestrictions(userId, systemRestrictions);
687 }
688 return effective;
689 }
690
691 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700692 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700693 if (DBG) {
694 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
695 }
696 mCachedEffectiveUserRestrictions.remove(userId);
697 }
698
699 private Bundle getEffectiveUserRestrictions(int userId) {
700 synchronized (mRestrictionsLock) {
701 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
702 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700703 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700704 mCachedEffectiveUserRestrictions.put(userId, restrictions);
705 }
706 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700707 }
708 }
709
Makoto Onuki068c54a2015-10-13 14:34:03 -0700710 /** @return a specific user restriction that's in effect currently. */
711 @Override
712 public boolean hasUserRestriction(String restrictionKey, int userId) {
713 Bundle restrictions = getEffectiveUserRestrictions(userId);
714 return restrictions != null && restrictions.getBoolean(restrictionKey);
715 }
716
717 /**
718 * @return UserRestrictions that are in effect currently. This always returns a new
719 * {@link Bundle}.
720 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700721 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800722 public Bundle getUserRestrictions(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700723 Bundle restrictions = getEffectiveUserRestrictions(userId);
724 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800725 }
726
727 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700728 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700729 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700730 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
731 setUserRestrictionNoCheck(key, value, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700732 }
733 }
734
735 @Override
736 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
737 checkSystemOrRoot("setSystemControlledUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700738 setUserRestrictionNoCheck(key, value, userId);
739 }
740
741 private void setUserRestrictionNoCheck(String key, boolean value, int userId) {
742 synchronized (mRestrictionsLock) {
743 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
744 // a copy.
745 final Bundle newRestrictions = new Bundle();
746 UserRestrictionsUtils.merge(newRestrictions, mBaseUserRestrictions.get(userId));
747 newRestrictions.putBoolean(key, value);
748
Fyodor Kupolov82402752015-10-28 14:54:51 -0700749 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700750 }
751 }
752
Makoto Onuki068c54a2015-10-13 14:34:03 -0700753 /**
754 * Optionally updating user restrictions, calculate the effective user restrictions by
755 * consulting {@link com.android.server.devicepolicy.DevicePolicyManagerService} and also
756 * apply it to {@link com.android.server.AppOpsService}.
757 * TODO applyUserRestrictionsLocked() should also apply to system settings.
758 *
759 * @param newRestrictions User restrictions to set. If null, only the effective restrictions
760 * will be updated. Note don't pass an existing Bundle in {@link #mBaseUserRestrictions}
761 * or {@link #mCachedEffectiveUserRestrictions}; that'll most likely cause a sub
762 * @param userId target user ID.
763 */
764 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700765 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700766 @Nullable Bundle newRestrictions, int userId) {
767 if (DBG) {
768 Log.d(LOG_TAG, "updateUserRestrictionsInternalLocked userId=" + userId
769 + " bundle=" + newRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800770 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700771 // Update system restrictions.
772 if (newRestrictions != null) {
773 // If newRestrictions == the current one, it's probably a bug.
774 Preconditions.checkState(mBaseUserRestrictions.get(userId) != newRestrictions);
775 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
776 != newRestrictions);
777 mBaseUserRestrictions.put(userId, newRestrictions);
Makoto Onuki9e935a32015-11-06 14:24:24 -0800778 scheduleWriteUser(mUsers.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700779 }
780
Fyodor Kupolov82402752015-10-28 14:54:51 -0700781 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700782
Makoto Onuki759a7632015-10-28 16:43:10 -0700783 mCachedEffectiveUserRestrictions.put(userId, effective);
784
Fyodor Kupolov82402752015-10-28 14:54:51 -0700785 applyUserRestrictionsLR(userId, effective);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800786 }
787
Makoto Onuki068c54a2015-10-13 14:34:03 -0700788 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700789 private void applyUserRestrictionsLR(int userId, Bundle newRestrictions) {
Makoto Onukid45a4a22015-11-02 17:17:38 -0800790 if (newRestrictions == null) {
791 newRestrictions = Bundle.EMPTY;
792 }
793
794 Bundle prevRestrictions = mAppliedUserRestrictions.get(userId);
795 if (prevRestrictions == null) {
796 prevRestrictions = Bundle.EMPTY;
797 }
Makoto Onuki4f160732015-10-27 17:15:38 -0700798
799 if (DBG) {
800 Log.d(LOG_TAG, "applyUserRestrictionsRL userId=" + userId
801 + " new=" + newRestrictions + " prev=" + prevRestrictions);
802 }
803
Makoto Onuki068c54a2015-10-13 14:34:03 -0700804 final long token = Binder.clearCallingIdentity();
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700805 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700806 mAppOpsService.setUserRestrictions(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700807 } catch (RemoteException e) {
808 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
809 } finally {
810 Binder.restoreCallingIdentity(token);
811 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700812
Makoto Onukid45a4a22015-11-02 17:17:38 -0800813 UserRestrictionsUtils.applyUserRestrictionsLR(
Makoto Onuki4f160732015-10-27 17:15:38 -0700814 mContext, userId, newRestrictions, prevRestrictions);
815
Makoto Onukid45a4a22015-11-02 17:17:38 -0800816 notifyUserRestrictionsListeners(userId, newRestrictions, prevRestrictions);
817
Makoto Onuki4f160732015-10-27 17:15:38 -0700818 mAppliedUserRestrictions.put(userId, new Bundle(newRestrictions));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700819 }
820
Makoto Onukid45a4a22015-11-02 17:17:38 -0800821 private void notifyUserRestrictionsListeners(final int userId,
822 Bundle newRestrictions, Bundle prevRestrictions) {
823
824 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
825 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
826
827 mHandler.post(new Runnable() {
828 @Override
829 public void run() {
830 final UserRestrictionsListener[] listeners;
831 synchronized (mUserRestrictionsListeners) {
832 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
833 mUserRestrictionsListeners.toArray(listeners);
834 }
835 for (int i = 0; i < listeners.length; i++) {
836 listeners[i].onUserRestrictionsChanged(userId,
837 newRestrictionsFinal, prevRestrictionsFinal);
838 }
839 }
840 });
841 }
842
Makoto Onuki068c54a2015-10-13 14:34:03 -0700843 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700844 private void updateEffectiveUserRestrictionsLR(int userId) {
845 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700846 }
847
848 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700849 private void updateEffectiveUserRestrictionsForAllUsersLR() {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700850 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700851 mCachedEffectiveUserRestrictions.clear();
852
Makoto Onuki068c54a2015-10-13 14:34:03 -0700853 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
854 // it on a handler.
855 final Runnable r = new Runnable() {
856 @Override
857 public void run() {
858 // Then get the list of running users.
859 final int[] runningUsers;
860 try {
861 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
862 } catch (RemoteException e) {
863 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
864 return;
865 }
866 // Then re-calculate the effective restrictions and apply, only for running users.
867 // It's okay if a new user has started after the getRunningUserIds() call,
868 // because we'll do the same thing (re-calculate the restrictions and apply)
869 // when we start a user.
870 // TODO: "Apply restrictions upon user start hasn't been implemented. Implement it.
871 synchronized (mRestrictionsLock) {
872 for (int i = 0; i < runningUsers.length; i++) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700873 updateUserRestrictionsInternalLR(null, runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700874 }
875 }
876 }
877 };
878 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700879 }
880
Amith Yamasani258848d2012-08-10 17:06:33 -0700881 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700882 * Check if we've hit the limit of how many users can be created.
883 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700884 private boolean isUserLimitReached() {
885 int count;
886 synchronized (mUsersLock) {
887 count = getAliveUsersExcludingGuestsCountLU();
888 }
889 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700890 }
891
892 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000893 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700894 checkManageUsersPermission("check if more managed profiles can be added.");
895 if (ActivityManager.isLowRamDeviceStatic()) {
896 return false;
897 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700898 if (!mContext.getPackageManager().hasSystemFeature(
899 PackageManager.FEATURE_MANAGED_USERS)) {
900 return false;
901 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100902 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000903 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
904 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
905 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100906 return false;
907 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700908 synchronized(mUsersLock) {
909 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100910 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700911 return false;
912 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000913 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
914 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -0700915 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000916 return usersCountAfterRemoving == 1
917 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700918 }
919 }
920
Fyodor Kupolov82402752015-10-28 14:54:51 -0700921 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700922 int aliveUserCount = 0;
923 final int totalUserCount = mUsers.size();
924 // Skip over users being removed
925 for (int i = 0; i < totalUserCount; i++) {
926 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700927 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700928 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700929 aliveUserCount++;
930 }
931 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700932 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700933 }
934
935 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700936 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700937 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700938 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700939 *
940 * @param message used as message if SecurityException is thrown
941 * @throws SecurityException if the caller is not system or root
942 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700943 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700944 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700945 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400946 && ActivityManager.checkComponentPermission(
947 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700948 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
949 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
950 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400951 }
952
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700953 private static void checkSystemOrRoot(String message) {
954 final int uid = Binder.getCallingUid();
955 if (uid != Process.SYSTEM_UID && uid != 0) {
956 throw new SecurityException("Only system may call: " + message);
957 }
958 }
959
Fyodor Kupolov82402752015-10-28 14:54:51 -0700960 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700961 try {
962 File dir = new File(mUsersDir, Integer.toString(info.id));
963 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100964 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700965 if (!dir.exists()) {
966 dir.mkdir();
967 FileUtils.setPermissions(
968 dir.getPath(),
969 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
970 -1, -1);
971 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700972 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100973 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
974 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700975 info.iconPath = file.getAbsolutePath();
976 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700977 try {
978 os.close();
979 } catch (IOException ioe) {
980 // What the ... !
981 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100982 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700983 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700984 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700985 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700986 }
987
Amith Yamasani0b285492011-04-14 17:35:23 -0700988 /**
989 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
990 * cache it elsewhere.
991 * @return the array of user ids.
992 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700993 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700994 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700995 return mUserIds;
996 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700997 }
998
Fyodor Kupolov82402752015-10-28 14:54:51 -0700999 private void readUserListLILP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001000 if (!mUserListFile.exists()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001001 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001002 return;
1003 }
1004 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001005 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001006 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001007 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001008 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001009 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001010 int type;
1011 while ((type = parser.next()) != XmlPullParser.START_TAG
1012 && type != XmlPullParser.END_DOCUMENT) {
1013 ;
1014 }
1015
1016 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001017 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001018 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001019 return;
1020 }
1021
Amith Yamasani2a003292012-08-14 18:25:45 -07001022 mNextSerialNumber = -1;
1023 if (parser.getName().equals(TAG_USERS)) {
1024 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1025 if (lastSerialNumber != null) {
1026 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1027 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001028 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1029 if (versionNumber != null) {
1030 mUserVersion = Integer.parseInt(versionNumber);
1031 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001032 }
1033
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001034 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301035 if (type == XmlPullParser.START_TAG) {
1036 final String name = parser.getName();
1037 if (name.equals(TAG_USER)) {
1038 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001039 UserInfo user = readUserLILP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001040
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301041 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001042 synchronized (mUsersLock) {
1043 mUsers.put(user.id, user);
1044 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1045 mNextSerialNumber = user.id + 1;
1046 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301047 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001048 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301049 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001050 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1051 && type != XmlPullParser.END_TAG) {
1052 if (type == XmlPullParser.START_TAG) {
1053 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001054 UserRestrictionsUtils
1055 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001056 }
1057 break;
1058 }
1059 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001060 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001061 }
1062 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001063 updateUserIds();
1064 upgradeIfNecessaryLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001065 } catch (IOException ioe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001066 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001067 } catch (XmlPullParserException pe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001068 fallbackToSingleUserLILP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001069 } finally {
1070 if (fis != null) {
1071 try {
1072 fis.close();
1073 } catch (IOException e) {
1074 }
1075 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001076 }
1077 }
1078
Amith Yamasani6f34b412012-10-22 18:19:27 -07001079 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001080 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001081 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001082 private void upgradeIfNecessaryLILP() {
Amith Yamasani6f34b412012-10-22 18:19:27 -07001083 int userVersion = mUserVersion;
1084 if (userVersion < 1) {
1085 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001086 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001087 if ("Primary".equals(user.name)) {
1088 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001089 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001090 }
1091 userVersion = 1;
1092 }
1093
Amith Yamasanibc9625052012-11-15 14:39:18 -08001094 if (userVersion < 2) {
1095 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001096 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001097 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1098 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001099 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001100 }
1101 userVersion = 2;
1102 }
1103
Amith Yamasani350962c2013-08-06 11:18:53 -07001104
Amith Yamasani5e486f52013-08-07 11:06:44 -07001105 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001106 userVersion = 4;
1107 }
1108
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001109 if (userVersion < 5) {
1110 initDefaultGuestRestrictions();
1111 userVersion = 5;
1112 }
1113
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001114 if (userVersion < 6) {
1115 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001116 synchronized (mUsersLock) {
1117 for (int i = 0; i < mUsers.size(); i++) {
1118 UserInfo user = mUsers.valueAt(i);
1119 // In non-split mode, only user 0 can have restricted profiles
1120 if (!splitSystemUser && user.isRestricted()
1121 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1122 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001123 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001124 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001125 }
1126 }
1127 userVersion = 6;
1128 }
1129
Amith Yamasani6f34b412012-10-22 18:19:27 -07001130 if (userVersion < USER_VERSION) {
1131 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1132 + USER_VERSION);
1133 } else {
1134 mUserVersion = userVersion;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001135 writeUserListLILP();
Amith Yamasani6f34b412012-10-22 18:19:27 -07001136 }
1137 }
1138
Fyodor Kupolov82402752015-10-28 14:54:51 -07001139 private void fallbackToSingleUserLILP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001140 int flags = UserInfo.FLAG_INITIALIZED;
1141 // In split system user mode, the admin and primary flags are assigned to the first human
1142 // user.
1143 if (!UserManager.isSplitSystemUser()) {
1144 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1145 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001146 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001147 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001148 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001149 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001150 synchronized (mUsersLock) {
1151 mUsers.put(system.id, system);
1152 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001153 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001154 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001155
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001156 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001157 synchronized (mRestrictionsLock) {
1158 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1159 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001160
Fyodor Kupolov82402752015-10-28 14:54:51 -07001161 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001162 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001163
Fyodor Kupolov82402752015-10-28 14:54:51 -07001164 writeUserListLILP();
1165 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001166 }
1167
Makoto Onuki9e935a32015-11-06 14:24:24 -08001168 private void scheduleWriteUser(UserInfo userInfo) {
1169 // No need to wrap it within a lock -- worst case, we'll just post the same message
1170 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001171 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1172 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1173 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1174 }
1175 }
1176
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001177 /*
1178 * Writes the user file in this format:
1179 *
1180 * <user flags="20039023" id="0">
1181 * <name>Primary</name>
1182 * </user>
1183 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001184 private void writeUserLP(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001185 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001186 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001187 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001188 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001189 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1190
1191 // XmlSerializer serializer = XmlUtils.serializerInstance();
1192 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001193 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001194 serializer.startDocument(null, true);
1195 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1196
1197 serializer.startTag(null, TAG_USER);
1198 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001199 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001200 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001201 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1202 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1203 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001204 if (userInfo.iconPath != null) {
1205 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1206 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001207 if (userInfo.partial) {
1208 serializer.attribute(null, ATTR_PARTIAL, "true");
1209 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001210 if (userInfo.guestToRemove) {
1211 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1212 }
Kenny Guy2a764942014-04-02 13:29:20 +01001213 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1214 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1215 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001216 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001217 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1218 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1219 Integer.toString(userInfo.restrictedProfileParentId));
1220 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001221 serializer.startTag(null, TAG_NAME);
1222 serializer.text(userInfo.name);
1223 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001224 Bundle restrictions;
1225 synchronized (mRestrictionsLock) {
1226 restrictions = mBaseUserRestrictions.get(userInfo.id);
1227 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001228 if (restrictions != null) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001229 UserRestrictionsUtils
1230 .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001231 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001232 serializer.endTag(null, TAG_USER);
1233
1234 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001235 userFile.finishWrite(fos);
1236 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001237 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001238 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001239 }
1240 }
1241
1242 /*
1243 * Writes the user list file in this format:
1244 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001245 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001246 * <user id="0"></user>
1247 * <user id="2"></user>
1248 * </users>
1249 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001250 private void writeUserListLILP() {
1251 // TODO Investigate removing a dependency on mInstallLock
Amith Yamasani742a6712011-05-04 14:49:28 -07001252 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001253 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001254 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001255 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001256 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1257
1258 // XmlSerializer serializer = XmlUtils.serializerInstance();
1259 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001260 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001261 serializer.startDocument(null, true);
1262 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1263
1264 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001265 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001266 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001267
Adam Lesinskieddeb492014-09-08 17:50:03 -07001268 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001269 UserRestrictionsUtils
1270 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301271 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001272 int[] userIdsToWrite;
1273 synchronized (mUsersLock) {
1274 userIdsToWrite = new int[mUsers.size()];
1275 for (int i = 0; i < userIdsToWrite.length; i++) {
1276 UserInfo user = mUsers.valueAt(i);
1277 userIdsToWrite[i] = user.id;
1278 }
1279 }
1280 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001281 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001282 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001283 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001284 }
1285
1286 serializer.endTag(null, TAG_USERS);
1287
1288 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001289 userListFile.finishWrite(fos);
1290 } catch (Exception e) {
1291 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001292 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001293 }
1294 }
1295
Fyodor Kupolov82402752015-10-28 14:54:51 -07001296 private UserInfo readUserLILP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001297 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001298 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001299 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001300 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001301 long creationTime = 0L;
1302 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001303 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001304 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001305 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001306 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001307 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001308
1309 FileInputStream fis = null;
1310 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001311 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001312 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001313 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001314 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001315 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001316 int type;
1317 while ((type = parser.next()) != XmlPullParser.START_TAG
1318 && type != XmlPullParser.END_DOCUMENT) {
1319 ;
1320 }
1321
1322 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001323 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001324 return null;
1325 }
1326
1327 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001328 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1329 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001330 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001331 return null;
1332 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001333 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1334 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001335 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001336 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1337 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001338 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1339 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001340 restrictedProfileParentId = readIntAttribute(parser,
1341 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001342 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1343 if ("true".equals(valueString)) {
1344 partial = true;
1345 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001346 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1347 if ("true".equals(valueString)) {
1348 guestToRemove = true;
1349 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001350
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001351 int outerDepth = parser.getDepth();
1352 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1353 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1354 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1355 continue;
1356 }
1357 String tag = parser.getName();
1358 if (TAG_NAME.equals(tag)) {
1359 type = parser.next();
1360 if (type == XmlPullParser.TEXT) {
1361 name = parser.getText();
1362 }
1363 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001364 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001365 }
1366 }
1367 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001368
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001369 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001370 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001371 userInfo.creationTime = creationTime;
1372 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001373 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001374 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001375 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001376 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001377 synchronized (mRestrictionsLock) {
1378 mBaseUserRestrictions.append(id, restrictions);
1379 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001380 return userInfo;
1381
1382 } catch (IOException ioe) {
1383 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001384 } finally {
1385 if (fis != null) {
1386 try {
1387 fis.close();
1388 } catch (IOException e) {
1389 }
1390 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001391 }
1392 return null;
1393 }
1394
Amith Yamasani920ace02012-09-20 22:15:37 -07001395 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1396 String valueString = parser.getAttributeValue(null, attr);
1397 if (valueString == null) return defaultValue;
1398 try {
1399 return Integer.parseInt(valueString);
1400 } catch (NumberFormatException nfe) {
1401 return defaultValue;
1402 }
1403 }
1404
1405 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1406 String valueString = parser.getAttributeValue(null, attr);
1407 if (valueString == null) return defaultValue;
1408 try {
1409 return Long.parseLong(valueString);
1410 } catch (NumberFormatException nfe) {
1411 return defaultValue;
1412 }
1413 }
1414
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001415 private boolean isPackageInstalled(String pkg, int userId) {
1416 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1417 PackageManager.GET_UNINSTALLED_PACKAGES,
1418 userId);
1419 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1420 return false;
1421 }
1422 return true;
1423 }
1424
Amith Yamasanib82add22013-07-09 11:24:44 -07001425 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001426 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001427 * Does not do any permissions checking.
1428 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001429 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001430 synchronized (mPackagesLock) {
1431 File dir = Environment.getUserSystemDirectory(userId);
1432 String[] files = dir.list();
1433 if (files == null) return;
1434 for (String fileName : files) {
1435 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1436 File resFile = new File(dir, fileName);
1437 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001438 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001439 }
1440 }
1441 }
1442 }
1443 }
1444
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001445 /**
1446 * Removes the app restrictions file for a specific package and user id, if it exists.
1447 */
1448 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1449 synchronized (mPackagesLock) {
1450 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001451 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001452 if (resFile.exists()) {
1453 resFile.delete();
1454 }
1455 }
1456 }
1457
Kenny Guya52dc3e2014-02-11 15:33:14 +00001458 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001459 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001460 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001461 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001462 }
1463
Amith Yamasani258848d2012-08-10 17:06:33 -07001464 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001465 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001466 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001467 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001468 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001469
Jessica Hummelbe81c802014-04-22 15:49:22 +01001470 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001471 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1472 UserManager.DISALLOW_ADD_USER, false)) {
1473 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1474 return null;
1475 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001476 if (ActivityManager.isLowRamDeviceStatic()) {
1477 return null;
1478 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001479 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001480 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001481 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001482 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001483 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001484 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001485 try {
1486 synchronized (mInstallLock) {
1487 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001488 UserInfo parent = null;
1489 if (parentId != UserHandle.USER_NULL) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001490 synchronized (mUsersLock) {
1491 parent = getUserInfoLU(parentId);
1492 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001493 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001494 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001495 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001496 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001497 return null;
1498 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001499 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001500 // If we're not adding a guest user or a managed profile and the limit has
1501 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001502 return null;
1503 }
1504 // If we're adding a guest and there already exists one, bail.
Fyodor Kupolov82402752015-10-28 14:54:51 -07001505 if (isGuest && findCurrentGuestUser() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001506 return null;
1507 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001508 // In legacy mode, restricted profile's parent can only be the owner user
1509 if (isRestricted && !UserManager.isSplitSystemUser()
1510 && (parentId != UserHandle.USER_SYSTEM)) {
1511 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1512 return null;
1513 }
1514 if (isRestricted && UserManager.isSplitSystemUser()) {
1515 if (parent == null) {
1516 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1517 + "specified");
1518 return null;
1519 }
1520 if (!parent.canHaveProfile()) {
1521 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1522 + "created for the specified parent user id " + parentId);
1523 return null;
1524 }
1525 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001526 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001527 // And if there is no device owner, we also assign the admin flag to primary
1528 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001529 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001530 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001531 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001532 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1533 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1534 if (devicePolicyManager == null
1535 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001536 flags |= UserInfo.FLAG_ADMIN;
1537 }
1538 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001539 userId = getNextAvailableId();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001540 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001541 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001542 long now = System.currentTimeMillis();
1543 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001544 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001545 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001546 mUsers.put(userId, userInfo);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001547 writeUserListLILP();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001548 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001549 if (isManagedProfile) {
1550 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1551 parent.profileGroupId = parent.id;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001552 scheduleWriteUser(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001553 }
1554 userInfo.profileGroupId = parent.profileGroupId;
1555 } else if (isRestricted) {
1556 if (!parent.canHaveProfile()) {
1557 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1558 }
1559 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1560 parent.restrictedProfileParentId = parent.id;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001561 scheduleWriteUser(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001562 }
1563 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001564 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001565 }
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001566
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001567 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001568 storage.createUserKey(userId, userInfo.serialNumber);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001569 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1570 final String volumeUuid = vol.getFsUuid();
1571 try {
1572 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1573 userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001574 storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001575 enforceSerialNumber(userDir, userInfo.serialNumber);
1576 } catch (IOException e) {
1577 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1578 }
1579 }
1580 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001581 userInfo.partial = false;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001582 scheduleWriteUser(userInfo);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001583 updateUserIds();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001584 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001585 synchronized (mRestrictionsLock) {
1586 mBaseUserRestrictions.append(userId, restrictions);
1587 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001588 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001589 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001590 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001591 if (userInfo != null) {
1592 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1593 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1594 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1595 android.Manifest.permission.MANAGE_USERS);
1596 }
1597 } finally {
1598 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001599 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001600 return userInfo;
1601 }
1602
Amith Yamasani0b285492011-04-14 17:35:23 -07001603 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001604 * @hide
1605 */
1606 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1607 checkManageUsersPermission("setupRestrictedProfile");
1608 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1609 if (user == null) {
1610 return null;
1611 }
1612 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1613 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1614 // the putIntForUser() will fail.
1615 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1616 android.provider.Settings.Secure.LOCATION_MODE,
1617 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1618 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1619 return user;
1620 }
1621
1622 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001623 * Find the current guest user. If the Guest user is partial,
1624 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001625 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001626 private UserInfo findCurrentGuestUser() {
1627 synchronized (mUsersLock) {
1628 final int size = mUsers.size();
1629 for (int i = 0; i < size; i++) {
1630 final UserInfo user = mUsers.valueAt(i);
1631 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1632 return user;
1633 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001634 }
1635 }
1636 return null;
1637 }
1638
1639 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001640 * Mark this guest user for deletion to allow us to create another guest
1641 * and switch to that user before actually removing this guest.
1642 * @param userHandle the userid of the current guest
1643 * @return whether the user could be marked for deletion
1644 */
1645 public boolean markGuestForDeletion(int userHandle) {
1646 checkManageUsersPermission("Only the system can remove users");
1647 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1648 UserManager.DISALLOW_REMOVE_USER, false)) {
1649 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1650 return false;
1651 }
1652
1653 long ident = Binder.clearCallingIdentity();
1654 try {
1655 final UserInfo user;
1656 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001657 synchronized (mUsersLock) {
1658 user = mUsers.get(userHandle);
1659 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1660 return false;
1661 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001662 }
1663 if (!user.isGuest()) {
1664 return false;
1665 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001666 // We set this to a guest user that is to be removed. This is a temporary state
1667 // where we are allowed to add new Guest users, even if this one is still not
1668 // removed. This user will still show up in getUserInfo() calls.
1669 // If we don't get around to removing this Guest user, it will be purged on next
1670 // startup.
1671 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001672 // Mark it as disabled, so that it isn't returned any more when
1673 // profiles are queried.
1674 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001675 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001676 }
1677 } finally {
1678 Binder.restoreCallingIdentity(ident);
1679 }
1680 return true;
1681 }
1682
1683 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001684 * Removes a user and all data directories created for that user. This method should be called
1685 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001686 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001687 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001688 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001689 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001690 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1691 UserManager.DISALLOW_REMOVE_USER, false)) {
1692 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1693 return false;
1694 }
1695
Kenny Guyee58b4f2014-05-23 15:19:53 +01001696 long ident = Binder.clearCallingIdentity();
1697 try {
1698 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001699 int currentUser = ActivityManager.getCurrentUser();
1700 if (currentUser == userHandle) {
1701 Log.w(LOG_TAG, "Current user cannot be removed");
1702 return false;
1703 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001704 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001705 synchronized (mUsersLock) {
1706 user = mUsers.get(userHandle);
1707 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1708 return false;
1709 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001710
Fyodor Kupolov82402752015-10-28 14:54:51 -07001711 // We remember deleted user IDs to prevent them from being
1712 // reused during the current boot; they can still be reused
1713 // after a reboot.
1714 mRemovingUserIds.put(userHandle, true);
1715 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001716
Kenny Guyee58b4f2014-05-23 15:19:53 +01001717 try {
1718 mAppOpsService.removeUser(userHandle);
1719 } catch (RemoteException e) {
1720 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1721 }
1722 // Set this to a partially created user, so that the user will be purged
1723 // on next startup, in case the runtime stops now before stopping and
1724 // removing the user completely.
1725 user.partial = true;
1726 // Mark it as disabled, so that it isn't returned any more when
1727 // profiles are queried.
1728 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001729 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001730 }
1731
1732 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1733 && user.isManagedProfile()) {
1734 // Send broadcast to notify system that the user removed was a
1735 // managed user.
1736 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1737 }
1738
1739 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1740 int res;
1741 try {
1742 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1743 new IStopUserCallback.Stub() {
1744 @Override
1745 public void userStopped(int userId) {
1746 finishRemoveUser(userId);
1747 }
1748 @Override
1749 public void userStopAborted(int userId) {
1750 }
1751 });
1752 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001753 return false;
1754 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001755 return res == ActivityManager.USER_OP_SUCCESS;
1756 } finally {
1757 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001758 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001759 }
1760
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001761 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001762 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001763 // Let other services shutdown any activity and clean up their state before completely
1764 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001765 long ident = Binder.clearCallingIdentity();
1766 try {
1767 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1768 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001769 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1770 android.Manifest.permission.MANAGE_USERS,
1771
1772 new BroadcastReceiver() {
1773 @Override
1774 public void onReceive(Context context, Intent intent) {
1775 if (DBG) {
1776 Slog.i(LOG_TAG,
1777 "USER_REMOVED broadcast sent, cleaning up user data "
1778 + userHandle);
1779 }
1780 new Thread() {
1781 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001782 // Clean up any ActivityManager state
1783 LocalServices.getService(ActivityManagerInternal.class)
1784 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001785 synchronized (mInstallLock) {
1786 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001787 removeUserStateLILP(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001788 }
1789 }
1790 }
1791 }.start();
1792 }
1793 },
1794
1795 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001796 } finally {
1797 Binder.restoreCallingIdentity(ident);
1798 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001799 }
1800
Fyodor Kupolov82402752015-10-28 14:54:51 -07001801 private void removeUserStateLILP(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001802 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001803 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001804 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001805
1806 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001807 synchronized (mUsersLock) {
1808 mUsers.remove(userHandle);
1809 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001810 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001811 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001812 userFile.delete();
1813 // Update the user list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001814 writeUserListLILP();
1815 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001816 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1817 }
1818
Amith Yamasani61f57372012-08-31 12:12:28 -07001819 private void removeDirectoryRecursive(File parent) {
1820 if (parent.isDirectory()) {
1821 String[] files = parent.list();
1822 for (String filename : files) {
1823 File child = new File(parent, filename);
1824 removeDirectoryRecursive(child);
1825 }
1826 }
1827 parent.delete();
1828 }
1829
Kenny Guyf8d3a232014-05-15 16:09:52 +01001830 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001831 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001832 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1833 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001834 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1835 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001836 }
1837
Amith Yamasani2a003292012-08-14 18:25:45 -07001838 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001839 public Bundle getApplicationRestrictions(String packageName) {
1840 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1841 }
1842
1843 @Override
1844 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001845 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001846 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001847 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001848 }
1849 synchronized (mPackagesLock) {
1850 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001851 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001852 }
1853 }
1854
1855 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001856 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001857 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001858 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001859 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001860 if (restrictions == null || restrictions.isEmpty()) {
1861 cleanAppRestrictionsForPackage(packageName, userId);
1862 } else {
1863 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001864 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001865 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001866 }
Robin Lee66e5d962014-04-09 16:44:21 +01001867
Kenny Guyd21b2182014-07-17 16:38:55 +01001868 if (isPackageInstalled(packageName, userId)) {
1869 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1870 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1871 changeIntent.setPackage(packageName);
1872 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1873 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1874 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001875 }
1876
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001877 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001878 mHandler.post(new Runnable() {
1879 @Override
1880 public void run() {
1881 List<ApplicationInfo> apps =
1882 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1883 userHandle).getList();
1884 final long ident = Binder.clearCallingIdentity();
1885 try {
1886 for (ApplicationInfo appInfo : apps) {
1887 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001888 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1889 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001890 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001891 userHandle);
1892 }
1893 }
1894 } finally {
1895 Binder.restoreCallingIdentity(ident);
1896 }
1897 }
1898 });
1899 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001900 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001901 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001902 try {
1903 return mContext.getPackageManager().getApplicationInfo(packageName,
1904 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1905 } catch (NameNotFoundException nnfe) {
1906 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001907 } finally {
1908 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001909 }
1910 }
1911
Fyodor Kupolov82402752015-10-28 14:54:51 -07001912 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001913 AtomicFile restrictionsFile =
1914 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1915 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001916 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001917 }
1918
1919 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001920 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001921 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001922 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001923 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001924 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001925 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001926
1927 FileInputStream fis = null;
1928 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001929 fis = restrictionsFile.openRead();
1930 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001931 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001932 XmlUtils.nextElement(parser);
1933 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001934 Slog.e(LOG_TAG, "Unable to read restrictions file "
1935 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001936 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001937 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001938 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1939 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001940 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001941 } catch (IOException|XmlPullParserException e) {
1942 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001943 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001944 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001945 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001946 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001947 }
1948
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001949 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1950 XmlPullParser parser) throws XmlPullParserException, IOException {
1951 int type = parser.getEventType();
1952 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1953 String key = parser.getAttributeValue(null, ATTR_KEY);
1954 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1955 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1956 if (multiple != null) {
1957 values.clear();
1958 int count = Integer.parseInt(multiple);
1959 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1960 if (type == XmlPullParser.START_TAG
1961 && parser.getName().equals(TAG_VALUE)) {
1962 values.add(parser.nextText().trim());
1963 count--;
1964 }
1965 }
1966 String [] valueStrings = new String[values.size()];
1967 values.toArray(valueStrings);
1968 restrictions.putStringArray(key, valueStrings);
1969 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1970 restrictions.putBundle(key, readBundleEntry(parser, values));
1971 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1972 final int outerDepth = parser.getDepth();
1973 ArrayList<Bundle> bundleList = new ArrayList<>();
1974 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1975 Bundle childBundle = readBundleEntry(parser, values);
1976 bundleList.add(childBundle);
1977 }
1978 restrictions.putParcelableArray(key,
1979 bundleList.toArray(new Bundle[bundleList.size()]));
1980 } else {
1981 String value = parser.nextText().trim();
1982 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1983 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1984 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1985 restrictions.putInt(key, Integer.parseInt(value));
1986 } else {
1987 restrictions.putString(key, value);
1988 }
1989 }
1990 }
1991 }
1992
1993 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1994 throws IOException, XmlPullParserException {
1995 Bundle childBundle = new Bundle();
1996 final int outerDepth = parser.getDepth();
1997 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1998 readEntry(childBundle, values, parser);
1999 }
2000 return childBundle;
2001 }
2002
Fyodor Kupolov82402752015-10-28 14:54:51 -07002003 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002004 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002005 AtomicFile restrictionsFile = new AtomicFile(
2006 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002007 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002008 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002009 }
2010
2011 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002012 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002013 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002014 try {
2015 fos = restrictionsFile.startWrite();
2016 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2017
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002018 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002019 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002020 serializer.startDocument(null, true);
2021 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2022
2023 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002024 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002025 serializer.endTag(null, TAG_RESTRICTIONS);
2026
2027 serializer.endDocument();
2028 restrictionsFile.finishWrite(fos);
2029 } catch (Exception e) {
2030 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002031 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2032 }
2033 }
2034
2035 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2036 throws IOException {
2037 for (String key : restrictions.keySet()) {
2038 Object value = restrictions.get(key);
2039 serializer.startTag(null, TAG_ENTRY);
2040 serializer.attribute(null, ATTR_KEY, key);
2041
2042 if (value instanceof Boolean) {
2043 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2044 serializer.text(value.toString());
2045 } else if (value instanceof Integer) {
2046 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2047 serializer.text(value.toString());
2048 } else if (value == null || value instanceof String) {
2049 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2050 serializer.text(value != null ? (String) value : "");
2051 } else if (value instanceof Bundle) {
2052 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2053 writeBundle((Bundle) value, serializer);
2054 } else if (value instanceof Parcelable[]) {
2055 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2056 Parcelable[] array = (Parcelable[]) value;
2057 for (Parcelable parcelable : array) {
2058 if (!(parcelable instanceof Bundle)) {
2059 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2060 }
2061 serializer.startTag(null, TAG_ENTRY);
2062 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2063 writeBundle((Bundle) parcelable, serializer);
2064 serializer.endTag(null, TAG_ENTRY);
2065 }
2066 } else {
2067 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2068 String[] values = (String[]) value;
2069 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2070 for (String choice : values) {
2071 serializer.startTag(null, TAG_VALUE);
2072 serializer.text(choice != null ? choice : "");
2073 serializer.endTag(null, TAG_VALUE);
2074 }
2075 }
2076 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002077 }
2078 }
2079
2080 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002081 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002082 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002083 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002084 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002085 }
2086 }
2087
2088 @Override
2089 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002090 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002091 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002092 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002093 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002094 }
2095 // Not found
2096 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002097 }
2098 }
2099
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002100 @Override
2101 public long getUserCreationTime(int userHandle) {
2102 int callingUserId = UserHandle.getCallingUserId();
2103 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002104 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002105 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002106 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002107 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002108 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002109 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002110 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002111 }
2112 }
2113 }
2114 if (userInfo == null) {
2115 throw new SecurityException("userHandle can only be the calling user or a managed "
2116 + "profile associated with this user");
2117 }
2118 return userInfo.creationTime;
2119 }
2120
Amith Yamasani0b285492011-04-14 17:35:23 -07002121 /**
2122 * Caches the list of user ids in an array, adjusting the array size when necessary.
2123 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002124 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002125 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002126 synchronized (mUsersLock) {
2127 final int userSize = mUsers.size();
2128 for (int i = 0; i < userSize; i++) {
2129 if (!mUsers.valueAt(i).partial) {
2130 num++;
2131 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002132 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002133 final int[] newUsers = new int[num];
2134 int n = 0;
2135 for (int i = 0; i < userSize; i++) {
2136 if (!mUsers.valueAt(i).partial) {
2137 newUsers[n++] = mUsers.keyAt(i);
2138 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002139 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002140 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002141 }
2142 }
2143
2144 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002145 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002146 * @param userId the user that was just foregrounded
2147 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002148 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002149 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002150 UserInfo user = getUserInfoNoChecks(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -07002151 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002152 if (user == null || user.partial) {
2153 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2154 return;
2155 }
2156 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002157 user.lastLoggedInTime = now;
Makoto Onuki9e935a32015-11-06 14:24:24 -08002158 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002159 }
2160 }
2161 }
2162
2163 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002164 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002165 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2166 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002167 * @return
2168 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002169 private int getNextAvailableId() {
2170 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002171 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002172 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002173 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002174 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002175 }
2176 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002177 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002178 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002179 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002180 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002181
Amith Yamasanifc95e702013-09-26 13:20:17 -07002182 private String packageToRestrictionsFileName(String packageName) {
2183 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2184 }
2185
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002186 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002187 * Enforce that serial number stored in user directory inode matches the
2188 * given expected value. Gracefully sets the serial number if currently
2189 * undefined.
2190 *
2191 * @throws IOException when problem extracting serial number, or serial
2192 * number is mismatched.
2193 */
2194 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2195 final int foundSerial = getSerialNumber(file);
2196 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2197
2198 if (foundSerial == -1) {
2199 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2200 try {
2201 setSerialNumber(file, serialNumber);
2202 } catch (IOException e) {
2203 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2204 }
2205
2206 } else if (foundSerial != serialNumber) {
2207 throw new IOException("Found serial number " + foundSerial
2208 + " doesn't match expected " + serialNumber);
2209 }
2210 }
2211
2212 /**
2213 * Set serial number stored in user directory inode.
2214 *
2215 * @throws IOException if serial number was already set
2216 */
2217 private static void setSerialNumber(File file, int serialNumber)
2218 throws IOException {
2219 try {
2220 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2221 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2222 } catch (ErrnoException e) {
2223 throw e.rethrowAsIOException();
2224 }
2225 }
2226
2227 /**
2228 * Return serial number stored in user directory inode.
2229 *
2230 * @return parsed serial number, or -1 if not set
2231 */
2232 private static int getSerialNumber(File file) throws IOException {
2233 try {
2234 final byte[] buf = new byte[256];
2235 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2236 final String serial = new String(buf, 0, len);
2237 try {
2238 return Integer.parseInt(serial);
2239 } catch (NumberFormatException e) {
2240 throw new IOException("Bad serial number: " + serial);
2241 }
2242 } catch (ErrnoException e) {
2243 if (e.errno == OsConstants.ENODATA) {
2244 return -1;
2245 } else {
2246 throw e.rethrowAsIOException();
2247 }
2248 }
2249 }
2250
Amith Yamasani920ace02012-09-20 22:15:37 -07002251 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002252 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2253 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2254 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2255 }
2256
2257 int onShellCommand(Shell shell, String cmd) {
2258 if (cmd == null) {
2259 return shell.handleDefaultCommands(cmd);
2260 }
2261
2262 final PrintWriter pw = shell.getOutPrintWriter();
2263 try {
2264 switch(cmd) {
2265 case "list":
2266 return runList(pw);
2267 }
2268 } catch (RemoteException e) {
2269 pw.println("Remote exception: " + e);
2270 }
2271 return -1;
2272 }
2273
2274 private int runList(PrintWriter pw) throws RemoteException {
2275 final IActivityManager am = ActivityManagerNative.getDefault();
2276 final List<UserInfo> users = getUsers(false);
2277 if (users == null) {
2278 pw.println("Error: couldn't get users");
2279 return 1;
2280 } else {
2281 pw.println("Users:");
2282 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002283 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002284 pw.println("\t" + users.get(i).toString() + running);
2285 }
2286 return 0;
2287 }
2288 }
2289
2290 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002291 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2292 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2293 != PackageManager.PERMISSION_GRANTED) {
2294 pw.println("Permission Denial: can't dump UserManager from from pid="
2295 + Binder.getCallingPid()
2296 + ", uid=" + Binder.getCallingUid()
2297 + " without permission "
2298 + android.Manifest.permission.DUMP);
2299 return;
2300 }
2301
2302 long now = System.currentTimeMillis();
2303 StringBuilder sb = new StringBuilder();
2304 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002305 synchronized (mUsersLock) {
2306 pw.println("Users:");
2307 for (int i = 0; i < mUsers.size(); i++) {
2308 UserInfo user = mUsers.valueAt(i);
2309 if (user == null) {
2310 continue;
2311 }
2312 pw.print(" "); pw.print(user);
2313 pw.print(" serialNo="); pw.print(user.serialNumber);
2314 if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2315 pw.print(" <removing> ");
2316 }
2317 if (user.partial) {
2318 pw.print(" <partial>");
2319 }
2320 pw.println();
2321 pw.print(" Created: ");
2322 if (user.creationTime == 0) {
2323 pw.println("<unknown>");
2324 } else {
2325 sb.setLength(0);
2326 TimeUtils.formatDuration(now - user.creationTime, sb);
2327 sb.append(" ago");
2328 pw.println(sb);
2329 }
2330 pw.print(" Last logged in: ");
2331 if (user.lastLoggedInTime == 0) {
2332 pw.println("<unknown>");
2333 } else {
2334 sb.setLength(0);
2335 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2336 sb.append(" ago");
2337 pw.println(sb);
2338 }
2339 pw.println(" Restrictions:");
2340 synchronized (mRestrictionsLock) {
2341 UserRestrictionsUtils.dumpRestrictions(
2342 pw, " ", mBaseUserRestrictions.get(user.id));
2343 pw.println(" Effective restrictions:");
2344 UserRestrictionsUtils.dumpRestrictions(
2345 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2346 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002347 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002348 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002349 pw.println();
2350 pw.println("Guest restrictions:");
2351 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002352 }
2353 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002354
2355 final class MainHandler extends Handler {
2356
2357 @Override
2358 public void handleMessage(Message msg) {
2359 switch (msg.what) {
2360 case WRITE_USER_MSG:
2361 removeMessages(WRITE_USER_MSG, msg.obj);
2362 synchronized (mPackagesLock) {
2363 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002364 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002365 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002366 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002367 }
2368 }
2369 }
2370 }
2371 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002372
2373 /**
2374 * @param userId
2375 * @return whether the user has been initialized yet
2376 */
2377 boolean isInitialized(int userId) {
2378 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2379 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002380
2381 private class LocalService extends UserManagerInternal {
2382
2383 @Override
2384 public Object getUserRestrictionsLock() {
2385 return mRestrictionsLock;
2386 }
2387
2388 @Override
2389 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002390 public void updateEffectiveUserRestrictionsLR(int userId) {
2391 UserManagerService.this.updateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002392 }
2393
2394 @Override
2395 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002396 public void updateEffectiveUserRestrictionsForAllUsersLR() {
2397 UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersLR();
Makoto Onuki068c54a2015-10-13 14:34:03 -07002398 }
2399
2400 @Override
2401 public Bundle getBaseUserRestrictions(int userId) {
2402 synchronized (mRestrictionsLock) {
2403 return mBaseUserRestrictions.get(userId);
2404 }
2405 }
2406
2407 @Override
2408 public void setBaseUserRestrictionsByDpmsForMigration(
2409 int userId, Bundle baseRestrictions) {
2410 synchronized (mRestrictionsLock) {
2411 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002412 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002413 }
2414
Fyodor Kupolov82402752015-10-28 14:54:51 -07002415 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002416 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002417 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002418 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002419 } else {
2420 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2421 }
2422 }
2423 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002424
2425 @Override
2426 public boolean getUserRestriction(int userId, String key) {
2427 return getUserRestrictions(userId).getBoolean(key);
2428 }
2429
2430 @Override
2431 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2432 synchronized (mUserRestrictionsListeners) {
2433 mUserRestrictionsListeners.add(listener);
2434 }
2435 }
2436
2437 @Override
2438 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2439 synchronized (mUserRestrictionsListeners) {
2440 mUserRestrictionsListeners.remove(listener);
2441 }
2442 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002443 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002444
2445 private class Shell extends ShellCommand {
2446 @Override
2447 public int onCommand(String cmd) {
2448 return onShellCommand(this, cmd);
2449 }
2450
2451 @Override
2452 public void onHelp() {
2453 final PrintWriter pw = getOutPrintWriter();
2454 pw.println("User manager (user) commands:");
2455 pw.println(" help");
2456 pw.println(" Print this help text.");
2457 pw.println("");
2458 pw.println(" list");
2459 pw.println(" Prints all users on the system.");
2460 }
2461 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002462}