blob: 47255923ef7dcf81f0b576713e2468f4997e0073 [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 Bayarrif05b9d02015-10-23 13:25:19 +0100412 if (!"file".equals(SystemProperties.get("ro.crypto.type", "none"))) {
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;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700638 scheduleWriteUserLP(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);
778 }
779
Fyodor Kupolov82402752015-10-28 14:54:51 -0700780 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700781
Makoto Onuki759a7632015-10-28 16:43:10 -0700782 mCachedEffectiveUserRestrictions.put(userId, effective);
783
Fyodor Kupolov82402752015-10-28 14:54:51 -0700784 applyUserRestrictionsLR(userId, effective);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800785 }
786
Makoto Onuki068c54a2015-10-13 14:34:03 -0700787 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700788 private void applyUserRestrictionsLR(int userId, Bundle newRestrictions) {
Makoto Onukid45a4a22015-11-02 17:17:38 -0800789 if (newRestrictions == null) {
790 newRestrictions = Bundle.EMPTY;
791 }
792
793 Bundle prevRestrictions = mAppliedUserRestrictions.get(userId);
794 if (prevRestrictions == null) {
795 prevRestrictions = Bundle.EMPTY;
796 }
Makoto Onuki4f160732015-10-27 17:15:38 -0700797
798 if (DBG) {
799 Log.d(LOG_TAG, "applyUserRestrictionsRL userId=" + userId
800 + " new=" + newRestrictions + " prev=" + prevRestrictions);
801 }
802
Makoto Onuki068c54a2015-10-13 14:34:03 -0700803 final long token = Binder.clearCallingIdentity();
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700804 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700805 mAppOpsService.setUserRestrictions(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700806 } catch (RemoteException e) {
807 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
808 } finally {
809 Binder.restoreCallingIdentity(token);
810 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700811
Makoto Onukid45a4a22015-11-02 17:17:38 -0800812 UserRestrictionsUtils.applyUserRestrictionsLR(
Makoto Onuki4f160732015-10-27 17:15:38 -0700813 mContext, userId, newRestrictions, prevRestrictions);
814
Makoto Onukid45a4a22015-11-02 17:17:38 -0800815 notifyUserRestrictionsListeners(userId, newRestrictions, prevRestrictions);
816
Makoto Onuki4f160732015-10-27 17:15:38 -0700817 mAppliedUserRestrictions.put(userId, new Bundle(newRestrictions));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700818 }
819
Makoto Onukid45a4a22015-11-02 17:17:38 -0800820 private void notifyUserRestrictionsListeners(final int userId,
821 Bundle newRestrictions, Bundle prevRestrictions) {
822
823 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
824 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
825
826 mHandler.post(new Runnable() {
827 @Override
828 public void run() {
829 final UserRestrictionsListener[] listeners;
830 synchronized (mUserRestrictionsListeners) {
831 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
832 mUserRestrictionsListeners.toArray(listeners);
833 }
834 for (int i = 0; i < listeners.length; i++) {
835 listeners[i].onUserRestrictionsChanged(userId,
836 newRestrictionsFinal, prevRestrictionsFinal);
837 }
838 }
839 });
840 }
841
Makoto Onuki068c54a2015-10-13 14:34:03 -0700842 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700843 private void updateEffectiveUserRestrictionsLR(int userId) {
844 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700845 }
846
847 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700848 private void updateEffectiveUserRestrictionsForAllUsersLR() {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700849 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700850 mCachedEffectiveUserRestrictions.clear();
851
Makoto Onuki068c54a2015-10-13 14:34:03 -0700852 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
853 // it on a handler.
854 final Runnable r = new Runnable() {
855 @Override
856 public void run() {
857 // Then get the list of running users.
858 final int[] runningUsers;
859 try {
860 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
861 } catch (RemoteException e) {
862 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
863 return;
864 }
865 // Then re-calculate the effective restrictions and apply, only for running users.
866 // It's okay if a new user has started after the getRunningUserIds() call,
867 // because we'll do the same thing (re-calculate the restrictions and apply)
868 // when we start a user.
869 // TODO: "Apply restrictions upon user start hasn't been implemented. Implement it.
870 synchronized (mRestrictionsLock) {
871 for (int i = 0; i < runningUsers.length; i++) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700872 updateUserRestrictionsInternalLR(null, runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700873 }
874 }
875 }
876 };
877 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700878 }
879
Amith Yamasani258848d2012-08-10 17:06:33 -0700880 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700881 * Check if we've hit the limit of how many users can be created.
882 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700883 private boolean isUserLimitReached() {
884 int count;
885 synchronized (mUsersLock) {
886 count = getAliveUsersExcludingGuestsCountLU();
887 }
888 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700889 }
890
891 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100892 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700893 checkManageUsersPermission("check if more managed profiles can be added.");
894 if (ActivityManager.isLowRamDeviceStatic()) {
895 return false;
896 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700897 if (!mContext.getPackageManager().hasSystemFeature(
898 PackageManager.FEATURE_MANAGED_USERS)) {
899 return false;
900 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100901 // Limit number of managed profiles that can be created
902 int managedProfilesCount = getProfiles(userId, true).size() - 1;
903 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
904 return false;
905 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700906 synchronized(mUsersLock) {
907 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100908 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700909 return false;
910 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700911 int usersCount = getAliveUsersExcludingGuestsCountLU();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700912 // We allow creating a managed profile in the special case where there is only one user.
913 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
914 }
915 }
916
Fyodor Kupolov82402752015-10-28 14:54:51 -0700917 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700918 int aliveUserCount = 0;
919 final int totalUserCount = mUsers.size();
920 // Skip over users being removed
921 for (int i = 0; i < totalUserCount; i++) {
922 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700923 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700924 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700925 aliveUserCount++;
926 }
927 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700928 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700929 }
930
931 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700932 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700933 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700934 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700935 *
936 * @param message used as message if SecurityException is thrown
937 * @throws SecurityException if the caller is not system or root
938 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700939 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700940 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700941 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400942 && ActivityManager.checkComponentPermission(
943 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700944 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
945 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
946 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400947 }
948
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700949 private static void checkSystemOrRoot(String message) {
950 final int uid = Binder.getCallingUid();
951 if (uid != Process.SYSTEM_UID && uid != 0) {
952 throw new SecurityException("Only system may call: " + message);
953 }
954 }
955
Fyodor Kupolov82402752015-10-28 14:54:51 -0700956 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700957 try {
958 File dir = new File(mUsersDir, Integer.toString(info.id));
959 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100960 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700961 if (!dir.exists()) {
962 dir.mkdir();
963 FileUtils.setPermissions(
964 dir.getPath(),
965 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
966 -1, -1);
967 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700968 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100969 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
970 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700971 info.iconPath = file.getAbsolutePath();
972 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700973 try {
974 os.close();
975 } catch (IOException ioe) {
976 // What the ... !
977 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100978 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700979 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700980 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700981 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700982 }
983
Amith Yamasani0b285492011-04-14 17:35:23 -0700984 /**
985 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
986 * cache it elsewhere.
987 * @return the array of user ids.
988 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700989 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700990 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700991 return mUserIds;
992 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700993 }
994
Fyodor Kupolov82402752015-10-28 14:54:51 -0700995 private void readUserListLILP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700996 if (!mUserListFile.exists()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700997 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700998 return;
999 }
1000 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001001 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001002 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001003 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001004 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001005 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001006 int type;
1007 while ((type = parser.next()) != XmlPullParser.START_TAG
1008 && type != XmlPullParser.END_DOCUMENT) {
1009 ;
1010 }
1011
1012 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001013 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001014 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001015 return;
1016 }
1017
Amith Yamasani2a003292012-08-14 18:25:45 -07001018 mNextSerialNumber = -1;
1019 if (parser.getName().equals(TAG_USERS)) {
1020 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1021 if (lastSerialNumber != null) {
1022 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1023 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001024 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1025 if (versionNumber != null) {
1026 mUserVersion = Integer.parseInt(versionNumber);
1027 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001028 }
1029
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001030 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301031 if (type == XmlPullParser.START_TAG) {
1032 final String name = parser.getName();
1033 if (name.equals(TAG_USER)) {
1034 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001035 UserInfo user = readUserLILP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001036
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301037 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001038 synchronized (mUsersLock) {
1039 mUsers.put(user.id, user);
1040 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1041 mNextSerialNumber = user.id + 1;
1042 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301043 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001044 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301045 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001046 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1047 && type != XmlPullParser.END_TAG) {
1048 if (type == XmlPullParser.START_TAG) {
1049 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001050 UserRestrictionsUtils
1051 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001052 }
1053 break;
1054 }
1055 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001056 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001057 }
1058 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001059 updateUserIds();
1060 upgradeIfNecessaryLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001061 } catch (IOException ioe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001062 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001063 } catch (XmlPullParserException pe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001064 fallbackToSingleUserLILP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001065 } finally {
1066 if (fis != null) {
1067 try {
1068 fis.close();
1069 } catch (IOException e) {
1070 }
1071 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001072 }
1073 }
1074
Amith Yamasani6f34b412012-10-22 18:19:27 -07001075 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001076 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001077 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001078 private void upgradeIfNecessaryLILP() {
Amith Yamasani6f34b412012-10-22 18:19:27 -07001079 int userVersion = mUserVersion;
1080 if (userVersion < 1) {
1081 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001082 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001083 if ("Primary".equals(user.name)) {
1084 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001085 scheduleWriteUserLP(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001086 }
1087 userVersion = 1;
1088 }
1089
Amith Yamasanibc9625052012-11-15 14:39:18 -08001090 if (userVersion < 2) {
1091 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001092 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001093 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1094 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001095 scheduleWriteUserLP(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001096 }
1097 userVersion = 2;
1098 }
1099
Amith Yamasani350962c2013-08-06 11:18:53 -07001100
Amith Yamasani5e486f52013-08-07 11:06:44 -07001101 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001102 userVersion = 4;
1103 }
1104
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001105 if (userVersion < 5) {
1106 initDefaultGuestRestrictions();
1107 userVersion = 5;
1108 }
1109
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001110 if (userVersion < 6) {
1111 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001112 synchronized (mUsersLock) {
1113 for (int i = 0; i < mUsers.size(); i++) {
1114 UserInfo user = mUsers.valueAt(i);
1115 // In non-split mode, only user 0 can have restricted profiles
1116 if (!splitSystemUser && user.isRestricted()
1117 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1118 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1119 scheduleWriteUserLP(user);
1120 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001121 }
1122 }
1123 userVersion = 6;
1124 }
1125
Amith Yamasani6f34b412012-10-22 18:19:27 -07001126 if (userVersion < USER_VERSION) {
1127 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1128 + USER_VERSION);
1129 } else {
1130 mUserVersion = userVersion;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001131 writeUserListLILP();
Amith Yamasani6f34b412012-10-22 18:19:27 -07001132 }
1133 }
1134
Fyodor Kupolov82402752015-10-28 14:54:51 -07001135 private void fallbackToSingleUserLILP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001136 int flags = UserInfo.FLAG_INITIALIZED;
1137 // In split system user mode, the admin and primary flags are assigned to the first human
1138 // user.
1139 if (!UserManager.isSplitSystemUser()) {
1140 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1141 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001142 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001143 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001144 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001145 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001146 synchronized (mUsersLock) {
1147 mUsers.put(system.id, system);
1148 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001149 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001150 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001151
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001152 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001153 synchronized (mRestrictionsLock) {
1154 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1155 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001156
Fyodor Kupolov82402752015-10-28 14:54:51 -07001157 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001158 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001159
Fyodor Kupolov82402752015-10-28 14:54:51 -07001160 writeUserListLILP();
1161 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001162 }
1163
Fyodor Kupolov82402752015-10-28 14:54:51 -07001164 private void scheduleWriteUserLP(UserInfo userInfo) {
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001165 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1166 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1167 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1168 }
1169 }
1170
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001171 /*
1172 * Writes the user file in this format:
1173 *
1174 * <user flags="20039023" id="0">
1175 * <name>Primary</name>
1176 * </user>
1177 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001178 private void writeUserLP(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001179 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001180 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001181 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001182 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001183 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1184
1185 // XmlSerializer serializer = XmlUtils.serializerInstance();
1186 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001187 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001188 serializer.startDocument(null, true);
1189 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1190
1191 serializer.startTag(null, TAG_USER);
1192 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001193 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001194 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001195 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1196 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1197 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001198 if (userInfo.iconPath != null) {
1199 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1200 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001201 if (userInfo.partial) {
1202 serializer.attribute(null, ATTR_PARTIAL, "true");
1203 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001204 if (userInfo.guestToRemove) {
1205 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1206 }
Kenny Guy2a764942014-04-02 13:29:20 +01001207 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1208 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1209 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001210 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001211 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1212 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1213 Integer.toString(userInfo.restrictedProfileParentId));
1214 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001215 serializer.startTag(null, TAG_NAME);
1216 serializer.text(userInfo.name);
1217 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001218 Bundle restrictions;
1219 synchronized (mRestrictionsLock) {
1220 restrictions = mBaseUserRestrictions.get(userInfo.id);
1221 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001222 if (restrictions != null) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001223 UserRestrictionsUtils
1224 .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001225 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001226 serializer.endTag(null, TAG_USER);
1227
1228 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001229 userFile.finishWrite(fos);
1230 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001231 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001232 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001233 }
1234 }
1235
1236 /*
1237 * Writes the user list file in this format:
1238 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001239 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001240 * <user id="0"></user>
1241 * <user id="2"></user>
1242 * </users>
1243 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001244 private void writeUserListLILP() {
1245 // TODO Investigate removing a dependency on mInstallLock
Amith Yamasani742a6712011-05-04 14:49:28 -07001246 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001247 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001248 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001249 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001250 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1251
1252 // XmlSerializer serializer = XmlUtils.serializerInstance();
1253 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001254 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001255 serializer.startDocument(null, true);
1256 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1257
1258 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001259 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001260 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001261
Adam Lesinskieddeb492014-09-08 17:50:03 -07001262 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001263 UserRestrictionsUtils
1264 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301265 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001266 int[] userIdsToWrite;
1267 synchronized (mUsersLock) {
1268 userIdsToWrite = new int[mUsers.size()];
1269 for (int i = 0; i < userIdsToWrite.length; i++) {
1270 UserInfo user = mUsers.valueAt(i);
1271 userIdsToWrite[i] = user.id;
1272 }
1273 }
1274 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001275 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001276 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001277 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001278 }
1279
1280 serializer.endTag(null, TAG_USERS);
1281
1282 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001283 userListFile.finishWrite(fos);
1284 } catch (Exception e) {
1285 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001286 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001287 }
1288 }
1289
Fyodor Kupolov82402752015-10-28 14:54:51 -07001290 private UserInfo readUserLILP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001291 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001292 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001293 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001294 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001295 long creationTime = 0L;
1296 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001297 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001298 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001299 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001300 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001301 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001302
1303 FileInputStream fis = null;
1304 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001305 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001306 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001307 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001308 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001309 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001310 int type;
1311 while ((type = parser.next()) != XmlPullParser.START_TAG
1312 && type != XmlPullParser.END_DOCUMENT) {
1313 ;
1314 }
1315
1316 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001317 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001318 return null;
1319 }
1320
1321 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001322 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1323 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001324 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001325 return null;
1326 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001327 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1328 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001329 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001330 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1331 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001332 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1333 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001334 restrictedProfileParentId = readIntAttribute(parser,
1335 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001336 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1337 if ("true".equals(valueString)) {
1338 partial = true;
1339 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001340 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1341 if ("true".equals(valueString)) {
1342 guestToRemove = true;
1343 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001344
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001345 int outerDepth = parser.getDepth();
1346 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1347 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1348 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1349 continue;
1350 }
1351 String tag = parser.getName();
1352 if (TAG_NAME.equals(tag)) {
1353 type = parser.next();
1354 if (type == XmlPullParser.TEXT) {
1355 name = parser.getText();
1356 }
1357 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001358 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001359 }
1360 }
1361 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001362
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001363 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001364 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001365 userInfo.creationTime = creationTime;
1366 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001367 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001368 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001369 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001370 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001371 synchronized (mRestrictionsLock) {
1372 mBaseUserRestrictions.append(id, restrictions);
1373 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001374 return userInfo;
1375
1376 } catch (IOException ioe) {
1377 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001378 } finally {
1379 if (fis != null) {
1380 try {
1381 fis.close();
1382 } catch (IOException e) {
1383 }
1384 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001385 }
1386 return null;
1387 }
1388
Amith Yamasani920ace02012-09-20 22:15:37 -07001389 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1390 String valueString = parser.getAttributeValue(null, attr);
1391 if (valueString == null) return defaultValue;
1392 try {
1393 return Integer.parseInt(valueString);
1394 } catch (NumberFormatException nfe) {
1395 return defaultValue;
1396 }
1397 }
1398
1399 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1400 String valueString = parser.getAttributeValue(null, attr);
1401 if (valueString == null) return defaultValue;
1402 try {
1403 return Long.parseLong(valueString);
1404 } catch (NumberFormatException nfe) {
1405 return defaultValue;
1406 }
1407 }
1408
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001409 private boolean isPackageInstalled(String pkg, int userId) {
1410 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1411 PackageManager.GET_UNINSTALLED_PACKAGES,
1412 userId);
1413 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1414 return false;
1415 }
1416 return true;
1417 }
1418
Amith Yamasanib82add22013-07-09 11:24:44 -07001419 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001420 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001421 * Does not do any permissions checking.
1422 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001423 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001424 synchronized (mPackagesLock) {
1425 File dir = Environment.getUserSystemDirectory(userId);
1426 String[] files = dir.list();
1427 if (files == null) return;
1428 for (String fileName : files) {
1429 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1430 File resFile = new File(dir, fileName);
1431 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001432 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001433 }
1434 }
1435 }
1436 }
1437 }
1438
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001439 /**
1440 * Removes the app restrictions file for a specific package and user id, if it exists.
1441 */
1442 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1443 synchronized (mPackagesLock) {
1444 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001445 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001446 if (resFile.exists()) {
1447 resFile.delete();
1448 }
1449 }
1450 }
1451
Kenny Guya52dc3e2014-02-11 15:33:14 +00001452 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001453 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001454 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001455 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001456 }
1457
Amith Yamasani258848d2012-08-10 17:06:33 -07001458 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001459 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001460 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001461 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001462 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001463
Jessica Hummelbe81c802014-04-22 15:49:22 +01001464 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001465 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1466 UserManager.DISALLOW_ADD_USER, false)) {
1467 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1468 return null;
1469 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001470 if (ActivityManager.isLowRamDeviceStatic()) {
1471 return null;
1472 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001473 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001474 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001475 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001476 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001477 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001478 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001479 try {
1480 synchronized (mInstallLock) {
1481 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001482 UserInfo parent = null;
1483 if (parentId != UserHandle.USER_NULL) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001484 synchronized (mUsersLock) {
1485 parent = getUserInfoLU(parentId);
1486 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001487 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001488 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001489 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1490 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001491 return null;
1492 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001493 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001494 // If we're not adding a guest user or a managed profile and the limit has
1495 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001496 return null;
1497 }
1498 // If we're adding a guest and there already exists one, bail.
Fyodor Kupolov82402752015-10-28 14:54:51 -07001499 if (isGuest && findCurrentGuestUser() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001500 return null;
1501 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001502 // In legacy mode, restricted profile's parent can only be the owner user
1503 if (isRestricted && !UserManager.isSplitSystemUser()
1504 && (parentId != UserHandle.USER_SYSTEM)) {
1505 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1506 return null;
1507 }
1508 if (isRestricted && UserManager.isSplitSystemUser()) {
1509 if (parent == null) {
1510 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1511 + "specified");
1512 return null;
1513 }
1514 if (!parent.canHaveProfile()) {
1515 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1516 + "created for the specified parent user id " + parentId);
1517 return null;
1518 }
1519 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001520 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001521 // And if there is no device owner, we also assign the admin flag to primary
1522 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001523 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001524 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001525 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001526 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1527 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1528 if (devicePolicyManager == null
1529 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001530 flags |= UserInfo.FLAG_ADMIN;
1531 }
1532 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001533 userId = getNextAvailableId();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001534 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001535 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001536 long now = System.currentTimeMillis();
1537 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001538 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001539 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001540 mUsers.put(userId, userInfo);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001541 writeUserListLILP();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001542 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001543 if (isManagedProfile) {
1544 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1545 parent.profileGroupId = parent.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001546 scheduleWriteUserLP(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001547 }
1548 userInfo.profileGroupId = parent.profileGroupId;
1549 } else if (isRestricted) {
1550 if (!parent.canHaveProfile()) {
1551 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1552 }
1553 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1554 parent.restrictedProfileParentId = parent.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001555 scheduleWriteUserLP(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001556 }
1557 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001558 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001559 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001560 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1561 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1562 final String volumeUuid = vol.getFsUuid();
1563 try {
1564 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1565 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001566 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001567 enforceSerialNumber(userDir, userInfo.serialNumber);
1568 } catch (IOException e) {
1569 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1570 }
1571 }
1572 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001573 userInfo.partial = false;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001574 scheduleWriteUserLP(userInfo);
1575 updateUserIds();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001576 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001577 synchronized (mRestrictionsLock) {
1578 mBaseUserRestrictions.append(userId, restrictions);
1579 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001580 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001581 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001582 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001583 if (userInfo != null) {
1584 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1585 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1586 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1587 android.Manifest.permission.MANAGE_USERS);
1588 }
1589 } finally {
1590 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001591 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001592 return userInfo;
1593 }
1594
Amith Yamasani0b285492011-04-14 17:35:23 -07001595 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001596 * @hide
1597 */
1598 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1599 checkManageUsersPermission("setupRestrictedProfile");
1600 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1601 if (user == null) {
1602 return null;
1603 }
1604 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1605 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1606 // the putIntForUser() will fail.
1607 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1608 android.provider.Settings.Secure.LOCATION_MODE,
1609 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1610 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1611 return user;
1612 }
1613
1614 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001615 * Find the current guest user. If the Guest user is partial,
1616 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001617 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001618 private UserInfo findCurrentGuestUser() {
1619 synchronized (mUsersLock) {
1620 final int size = mUsers.size();
1621 for (int i = 0; i < size; i++) {
1622 final UserInfo user = mUsers.valueAt(i);
1623 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1624 return user;
1625 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001626 }
1627 }
1628 return null;
1629 }
1630
1631 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001632 * Mark this guest user for deletion to allow us to create another guest
1633 * and switch to that user before actually removing this guest.
1634 * @param userHandle the userid of the current guest
1635 * @return whether the user could be marked for deletion
1636 */
1637 public boolean markGuestForDeletion(int userHandle) {
1638 checkManageUsersPermission("Only the system can remove users");
1639 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1640 UserManager.DISALLOW_REMOVE_USER, false)) {
1641 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1642 return false;
1643 }
1644
1645 long ident = Binder.clearCallingIdentity();
1646 try {
1647 final UserInfo user;
1648 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001649 synchronized (mUsersLock) {
1650 user = mUsers.get(userHandle);
1651 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1652 return false;
1653 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001654 }
1655 if (!user.isGuest()) {
1656 return false;
1657 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001658 // We set this to a guest user that is to be removed. This is a temporary state
1659 // where we are allowed to add new Guest users, even if this one is still not
1660 // removed. This user will still show up in getUserInfo() calls.
1661 // If we don't get around to removing this Guest user, it will be purged on next
1662 // startup.
1663 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001664 // Mark it as disabled, so that it isn't returned any more when
1665 // profiles are queried.
1666 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001667 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001668 }
1669 } finally {
1670 Binder.restoreCallingIdentity(ident);
1671 }
1672 return true;
1673 }
1674
1675 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001676 * Removes a user and all data directories created for that user. This method should be called
1677 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001678 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001679 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001680 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001681 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001682 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1683 UserManager.DISALLOW_REMOVE_USER, false)) {
1684 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1685 return false;
1686 }
1687
Kenny Guyee58b4f2014-05-23 15:19:53 +01001688 long ident = Binder.clearCallingIdentity();
1689 try {
1690 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001691 int currentUser = ActivityManager.getCurrentUser();
1692 if (currentUser == userHandle) {
1693 Log.w(LOG_TAG, "Current user cannot be removed");
1694 return false;
1695 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001696 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001697 synchronized (mUsersLock) {
1698 user = mUsers.get(userHandle);
1699 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1700 return false;
1701 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001702
Fyodor Kupolov82402752015-10-28 14:54:51 -07001703 // We remember deleted user IDs to prevent them from being
1704 // reused during the current boot; they can still be reused
1705 // after a reboot.
1706 mRemovingUserIds.put(userHandle, true);
1707 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001708
Kenny Guyee58b4f2014-05-23 15:19:53 +01001709 try {
1710 mAppOpsService.removeUser(userHandle);
1711 } catch (RemoteException e) {
1712 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1713 }
1714 // Set this to a partially created user, so that the user will be purged
1715 // on next startup, in case the runtime stops now before stopping and
1716 // removing the user completely.
1717 user.partial = true;
1718 // Mark it as disabled, so that it isn't returned any more when
1719 // profiles are queried.
1720 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001721 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001722 }
1723
1724 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1725 && user.isManagedProfile()) {
1726 // Send broadcast to notify system that the user removed was a
1727 // managed user.
1728 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1729 }
1730
1731 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1732 int res;
1733 try {
1734 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1735 new IStopUserCallback.Stub() {
1736 @Override
1737 public void userStopped(int userId) {
1738 finishRemoveUser(userId);
1739 }
1740 @Override
1741 public void userStopAborted(int userId) {
1742 }
1743 });
1744 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001745 return false;
1746 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001747 return res == ActivityManager.USER_OP_SUCCESS;
1748 } finally {
1749 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001750 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001751 }
1752
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001753 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001754 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001755 // Let other services shutdown any activity and clean up their state before completely
1756 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001757 long ident = Binder.clearCallingIdentity();
1758 try {
1759 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1760 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001761 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1762 android.Manifest.permission.MANAGE_USERS,
1763
1764 new BroadcastReceiver() {
1765 @Override
1766 public void onReceive(Context context, Intent intent) {
1767 if (DBG) {
1768 Slog.i(LOG_TAG,
1769 "USER_REMOVED broadcast sent, cleaning up user data "
1770 + userHandle);
1771 }
1772 new Thread() {
1773 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001774 // Clean up any ActivityManager state
1775 LocalServices.getService(ActivityManagerInternal.class)
1776 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001777 synchronized (mInstallLock) {
1778 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001779 removeUserStateLILP(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001780 }
1781 }
1782 }
1783 }.start();
1784 }
1785 },
1786
1787 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001788 } finally {
1789 Binder.restoreCallingIdentity(ident);
1790 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001791 }
1792
Fyodor Kupolov82402752015-10-28 14:54:51 -07001793 private void removeUserStateLILP(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001794 mContext.getSystemService(StorageManager.class)
1795 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001796 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001797 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001798
1799 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001800 synchronized (mUsersLock) {
1801 mUsers.remove(userHandle);
1802 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001803 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001804 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001805 userFile.delete();
1806 // Update the user list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001807 writeUserListLILP();
1808 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001809 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1810 }
1811
Amith Yamasani61f57372012-08-31 12:12:28 -07001812 private void removeDirectoryRecursive(File parent) {
1813 if (parent.isDirectory()) {
1814 String[] files = parent.list();
1815 for (String filename : files) {
1816 File child = new File(parent, filename);
1817 removeDirectoryRecursive(child);
1818 }
1819 }
1820 parent.delete();
1821 }
1822
Kenny Guyf8d3a232014-05-15 16:09:52 +01001823 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001824 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001825 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1826 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001827 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1828 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001829 }
1830
Amith Yamasani2a003292012-08-14 18:25:45 -07001831 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001832 public Bundle getApplicationRestrictions(String packageName) {
1833 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1834 }
1835
1836 @Override
1837 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001838 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001839 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001840 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001841 }
1842 synchronized (mPackagesLock) {
1843 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001844 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001845 }
1846 }
1847
1848 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001849 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001850 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001851 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001852 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001853 if (restrictions == null || restrictions.isEmpty()) {
1854 cleanAppRestrictionsForPackage(packageName, userId);
1855 } else {
1856 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001857 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001858 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001859 }
Robin Lee66e5d962014-04-09 16:44:21 +01001860
Kenny Guyd21b2182014-07-17 16:38:55 +01001861 if (isPackageInstalled(packageName, userId)) {
1862 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1863 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1864 changeIntent.setPackage(packageName);
1865 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1866 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1867 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001868 }
1869
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001870 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001871 mHandler.post(new Runnable() {
1872 @Override
1873 public void run() {
1874 List<ApplicationInfo> apps =
1875 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1876 userHandle).getList();
1877 final long ident = Binder.clearCallingIdentity();
1878 try {
1879 for (ApplicationInfo appInfo : apps) {
1880 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001881 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1882 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001883 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001884 userHandle);
1885 }
1886 }
1887 } finally {
1888 Binder.restoreCallingIdentity(ident);
1889 }
1890 }
1891 });
1892 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001893 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001894 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001895 try {
1896 return mContext.getPackageManager().getApplicationInfo(packageName,
1897 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1898 } catch (NameNotFoundException nnfe) {
1899 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001900 } finally {
1901 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001902 }
1903 }
1904
Fyodor Kupolov82402752015-10-28 14:54:51 -07001905 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001906 AtomicFile restrictionsFile =
1907 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1908 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001909 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001910 }
1911
1912 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001913 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001914 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001915 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001916 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001917 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001918 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001919
1920 FileInputStream fis = null;
1921 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001922 fis = restrictionsFile.openRead();
1923 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001924 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001925 XmlUtils.nextElement(parser);
1926 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001927 Slog.e(LOG_TAG, "Unable to read restrictions file "
1928 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001929 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001930 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001931 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1932 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001933 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001934 } catch (IOException|XmlPullParserException e) {
1935 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001936 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001937 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001938 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001939 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001940 }
1941
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001942 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1943 XmlPullParser parser) throws XmlPullParserException, IOException {
1944 int type = parser.getEventType();
1945 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1946 String key = parser.getAttributeValue(null, ATTR_KEY);
1947 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1948 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1949 if (multiple != null) {
1950 values.clear();
1951 int count = Integer.parseInt(multiple);
1952 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1953 if (type == XmlPullParser.START_TAG
1954 && parser.getName().equals(TAG_VALUE)) {
1955 values.add(parser.nextText().trim());
1956 count--;
1957 }
1958 }
1959 String [] valueStrings = new String[values.size()];
1960 values.toArray(valueStrings);
1961 restrictions.putStringArray(key, valueStrings);
1962 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1963 restrictions.putBundle(key, readBundleEntry(parser, values));
1964 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1965 final int outerDepth = parser.getDepth();
1966 ArrayList<Bundle> bundleList = new ArrayList<>();
1967 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1968 Bundle childBundle = readBundleEntry(parser, values);
1969 bundleList.add(childBundle);
1970 }
1971 restrictions.putParcelableArray(key,
1972 bundleList.toArray(new Bundle[bundleList.size()]));
1973 } else {
1974 String value = parser.nextText().trim();
1975 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1976 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1977 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1978 restrictions.putInt(key, Integer.parseInt(value));
1979 } else {
1980 restrictions.putString(key, value);
1981 }
1982 }
1983 }
1984 }
1985
1986 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1987 throws IOException, XmlPullParserException {
1988 Bundle childBundle = new Bundle();
1989 final int outerDepth = parser.getDepth();
1990 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1991 readEntry(childBundle, values, parser);
1992 }
1993 return childBundle;
1994 }
1995
Fyodor Kupolov82402752015-10-28 14:54:51 -07001996 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001997 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001998 AtomicFile restrictionsFile = new AtomicFile(
1999 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002000 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002001 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002002 }
2003
2004 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002005 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002006 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002007 try {
2008 fos = restrictionsFile.startWrite();
2009 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2010
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002011 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002012 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002013 serializer.startDocument(null, true);
2014 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2015
2016 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002017 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002018 serializer.endTag(null, TAG_RESTRICTIONS);
2019
2020 serializer.endDocument();
2021 restrictionsFile.finishWrite(fos);
2022 } catch (Exception e) {
2023 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002024 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2025 }
2026 }
2027
2028 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2029 throws IOException {
2030 for (String key : restrictions.keySet()) {
2031 Object value = restrictions.get(key);
2032 serializer.startTag(null, TAG_ENTRY);
2033 serializer.attribute(null, ATTR_KEY, key);
2034
2035 if (value instanceof Boolean) {
2036 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2037 serializer.text(value.toString());
2038 } else if (value instanceof Integer) {
2039 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2040 serializer.text(value.toString());
2041 } else if (value == null || value instanceof String) {
2042 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2043 serializer.text(value != null ? (String) value : "");
2044 } else if (value instanceof Bundle) {
2045 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2046 writeBundle((Bundle) value, serializer);
2047 } else if (value instanceof Parcelable[]) {
2048 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2049 Parcelable[] array = (Parcelable[]) value;
2050 for (Parcelable parcelable : array) {
2051 if (!(parcelable instanceof Bundle)) {
2052 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2053 }
2054 serializer.startTag(null, TAG_ENTRY);
2055 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2056 writeBundle((Bundle) parcelable, serializer);
2057 serializer.endTag(null, TAG_ENTRY);
2058 }
2059 } else {
2060 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2061 String[] values = (String[]) value;
2062 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2063 for (String choice : values) {
2064 serializer.startTag(null, TAG_VALUE);
2065 serializer.text(choice != null ? choice : "");
2066 serializer.endTag(null, TAG_VALUE);
2067 }
2068 }
2069 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002070 }
2071 }
2072
2073 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002074 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002075 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002076 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002077 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002078 }
2079 }
2080
2081 @Override
2082 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002083 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002084 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002085 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002086 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002087 }
2088 // Not found
2089 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002090 }
2091 }
2092
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002093 @Override
2094 public long getUserCreationTime(int userHandle) {
2095 int callingUserId = UserHandle.getCallingUserId();
2096 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002097 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002098 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002099 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002100 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002101 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002102 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002103 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002104 }
2105 }
2106 }
2107 if (userInfo == null) {
2108 throw new SecurityException("userHandle can only be the calling user or a managed "
2109 + "profile associated with this user");
2110 }
2111 return userInfo.creationTime;
2112 }
2113
Amith Yamasani0b285492011-04-14 17:35:23 -07002114 /**
2115 * Caches the list of user ids in an array, adjusting the array size when necessary.
2116 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002117 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002118 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002119 synchronized (mUsersLock) {
2120 final int userSize = mUsers.size();
2121 for (int i = 0; i < userSize; i++) {
2122 if (!mUsers.valueAt(i).partial) {
2123 num++;
2124 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002125 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002126 final int[] newUsers = new int[num];
2127 int n = 0;
2128 for (int i = 0; i < userSize; i++) {
2129 if (!mUsers.valueAt(i).partial) {
2130 newUsers[n++] = mUsers.keyAt(i);
2131 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002132 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002133 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002134 }
2135 }
2136
2137 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002138 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002139 * @param userId the user that was just foregrounded
2140 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002141 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002142 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002143 UserInfo user = getUserInfoNoChecks(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -07002144 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002145 if (user == null || user.partial) {
2146 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2147 return;
2148 }
2149 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002150 user.lastLoggedInTime = now;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002151 scheduleWriteUserLP(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002152 }
2153 }
2154 }
2155
2156 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002157 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002158 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2159 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002160 * @return
2161 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002162 private int getNextAvailableId() {
2163 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002164 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002165 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002166 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002167 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002168 }
2169 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002170 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002171 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002172 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002173 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002174
Amith Yamasanifc95e702013-09-26 13:20:17 -07002175 private String packageToRestrictionsFileName(String packageName) {
2176 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2177 }
2178
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002179 /**
2180 * Create new {@code /data/user/[id]} directory and sets default
2181 * permissions.
2182 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002183 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2184 final StorageManager storage = context.getSystemService(StorageManager.class);
2185 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2186 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002187 }
2188
2189 /**
2190 * Enforce that serial number stored in user directory inode matches the
2191 * given expected value. Gracefully sets the serial number if currently
2192 * undefined.
2193 *
2194 * @throws IOException when problem extracting serial number, or serial
2195 * number is mismatched.
2196 */
2197 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2198 final int foundSerial = getSerialNumber(file);
2199 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2200
2201 if (foundSerial == -1) {
2202 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2203 try {
2204 setSerialNumber(file, serialNumber);
2205 } catch (IOException e) {
2206 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2207 }
2208
2209 } else if (foundSerial != serialNumber) {
2210 throw new IOException("Found serial number " + foundSerial
2211 + " doesn't match expected " + serialNumber);
2212 }
2213 }
2214
2215 /**
2216 * Set serial number stored in user directory inode.
2217 *
2218 * @throws IOException if serial number was already set
2219 */
2220 private static void setSerialNumber(File file, int serialNumber)
2221 throws IOException {
2222 try {
2223 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2224 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2225 } catch (ErrnoException e) {
2226 throw e.rethrowAsIOException();
2227 }
2228 }
2229
2230 /**
2231 * Return serial number stored in user directory inode.
2232 *
2233 * @return parsed serial number, or -1 if not set
2234 */
2235 private static int getSerialNumber(File file) throws IOException {
2236 try {
2237 final byte[] buf = new byte[256];
2238 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2239 final String serial = new String(buf, 0, len);
2240 try {
2241 return Integer.parseInt(serial);
2242 } catch (NumberFormatException e) {
2243 throw new IOException("Bad serial number: " + serial);
2244 }
2245 } catch (ErrnoException e) {
2246 if (e.errno == OsConstants.ENODATA) {
2247 return -1;
2248 } else {
2249 throw e.rethrowAsIOException();
2250 }
2251 }
2252 }
2253
Amith Yamasani920ace02012-09-20 22:15:37 -07002254 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002255 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2256 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2257 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2258 }
2259
2260 int onShellCommand(Shell shell, String cmd) {
2261 if (cmd == null) {
2262 return shell.handleDefaultCommands(cmd);
2263 }
2264
2265 final PrintWriter pw = shell.getOutPrintWriter();
2266 try {
2267 switch(cmd) {
2268 case "list":
2269 return runList(pw);
2270 }
2271 } catch (RemoteException e) {
2272 pw.println("Remote exception: " + e);
2273 }
2274 return -1;
2275 }
2276
2277 private int runList(PrintWriter pw) throws RemoteException {
2278 final IActivityManager am = ActivityManagerNative.getDefault();
2279 final List<UserInfo> users = getUsers(false);
2280 if (users == null) {
2281 pw.println("Error: couldn't get users");
2282 return 1;
2283 } else {
2284 pw.println("Users:");
2285 for (int i = 0; i < users.size(); i++) {
2286 String running = am.isUserRunning(users.get(i).id, false) ? " running" : "";
2287 pw.println("\t" + users.get(i).toString() + running);
2288 }
2289 return 0;
2290 }
2291 }
2292
2293 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002294 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2295 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2296 != PackageManager.PERMISSION_GRANTED) {
2297 pw.println("Permission Denial: can't dump UserManager from from pid="
2298 + Binder.getCallingPid()
2299 + ", uid=" + Binder.getCallingUid()
2300 + " without permission "
2301 + android.Manifest.permission.DUMP);
2302 return;
2303 }
2304
2305 long now = System.currentTimeMillis();
2306 StringBuilder sb = new StringBuilder();
2307 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002308 synchronized (mUsersLock) {
2309 pw.println("Users:");
2310 for (int i = 0; i < mUsers.size(); i++) {
2311 UserInfo user = mUsers.valueAt(i);
2312 if (user == null) {
2313 continue;
2314 }
2315 pw.print(" "); pw.print(user);
2316 pw.print(" serialNo="); pw.print(user.serialNumber);
2317 if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2318 pw.print(" <removing> ");
2319 }
2320 if (user.partial) {
2321 pw.print(" <partial>");
2322 }
2323 pw.println();
2324 pw.print(" Created: ");
2325 if (user.creationTime == 0) {
2326 pw.println("<unknown>");
2327 } else {
2328 sb.setLength(0);
2329 TimeUtils.formatDuration(now - user.creationTime, sb);
2330 sb.append(" ago");
2331 pw.println(sb);
2332 }
2333 pw.print(" Last logged in: ");
2334 if (user.lastLoggedInTime == 0) {
2335 pw.println("<unknown>");
2336 } else {
2337 sb.setLength(0);
2338 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2339 sb.append(" ago");
2340 pw.println(sb);
2341 }
2342 pw.println(" Restrictions:");
2343 synchronized (mRestrictionsLock) {
2344 UserRestrictionsUtils.dumpRestrictions(
2345 pw, " ", mBaseUserRestrictions.get(user.id));
2346 pw.println(" Effective restrictions:");
2347 UserRestrictionsUtils.dumpRestrictions(
2348 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2349 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002350 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002351 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002352 pw.println();
2353 pw.println("Guest restrictions:");
2354 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002355 }
2356 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002357
2358 final class MainHandler extends Handler {
2359
2360 @Override
2361 public void handleMessage(Message msg) {
2362 switch (msg.what) {
2363 case WRITE_USER_MSG:
2364 removeMessages(WRITE_USER_MSG, msg.obj);
2365 synchronized (mPackagesLock) {
2366 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002367 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002368 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002369 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002370 }
2371 }
2372 }
2373 }
2374 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002375
2376 /**
2377 * @param userId
2378 * @return whether the user has been initialized yet
2379 */
2380 boolean isInitialized(int userId) {
2381 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2382 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002383
2384 private class LocalService extends UserManagerInternal {
2385
2386 @Override
2387 public Object getUserRestrictionsLock() {
2388 return mRestrictionsLock;
2389 }
2390
2391 @Override
2392 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002393 public void updateEffectiveUserRestrictionsLR(int userId) {
2394 UserManagerService.this.updateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002395 }
2396
2397 @Override
2398 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002399 public void updateEffectiveUserRestrictionsForAllUsersLR() {
2400 UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersLR();
Makoto Onuki068c54a2015-10-13 14:34:03 -07002401 }
2402
2403 @Override
2404 public Bundle getBaseUserRestrictions(int userId) {
2405 synchronized (mRestrictionsLock) {
2406 return mBaseUserRestrictions.get(userId);
2407 }
2408 }
2409
2410 @Override
2411 public void setBaseUserRestrictionsByDpmsForMigration(
2412 int userId, Bundle baseRestrictions) {
2413 synchronized (mRestrictionsLock) {
2414 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002415 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002416 }
2417
Fyodor Kupolov82402752015-10-28 14:54:51 -07002418 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002419 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002420 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002421 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002422 } else {
2423 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2424 }
2425 }
2426 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002427
2428 @Override
2429 public boolean getUserRestriction(int userId, String key) {
2430 return getUserRestrictions(userId).getBoolean(key);
2431 }
2432
2433 @Override
2434 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2435 synchronized (mUserRestrictionsListeners) {
2436 mUserRestrictionsListeners.add(listener);
2437 }
2438 }
2439
2440 @Override
2441 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2442 synchronized (mUserRestrictionsListeners) {
2443 mUserRestrictionsListeners.remove(listener);
2444 }
2445 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002446 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002447
2448 private class Shell extends ShellCommand {
2449 @Override
2450 public int onCommand(String cmd) {
2451 return onShellCommand(this, cmd);
2452 }
2453
2454 @Override
2455 public void onHelp() {
2456 final PrintWriter pw = getOutPrintWriter();
2457 pw.println("User manager (user) commands:");
2458 pw.println(" help");
2459 pw.println(" Print this help text.");
2460 pw.println("");
2461 pw.println(" list");
2462 pw.println(" Prints all users on the system.");
2463 }
2464 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002465}