blob: 4929960bad93b90ecf7eb50f8f696131162e9af6 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chen594f2082015-08-18 11:04:20 -070019import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070020import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070023import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070024import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070025import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070026import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070027import android.app.admin.DevicePolicyManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070028import android.app.admin.DevicePolicyManagerInternal;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070029import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070030import android.content.Context;
31import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070032import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070033import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080034import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070035import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070036import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080038import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070039import android.os.Environment;
40import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080041import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080043import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010044import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070045import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070047import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070048import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040049import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070050import android.os.ShellCommand;
Clara Bayarrif05b9d02015-10-23 13:25:19 +010051import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070052import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070053import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070054import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080055import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010056import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070057import android.os.storage.VolumeInfo;
58import android.system.ErrnoException;
59import android.system.Os;
60import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070061import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070062import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import android.util.Slog;
64import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080065import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070066import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import android.util.Xml;
68
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070070import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040071import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080072import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070073import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070074import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070075import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080076
77import org.xmlpull.v1.XmlPullParser;
78import org.xmlpull.v1.XmlPullParserException;
79import org.xmlpull.v1.XmlSerializer;
80
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import java.io.BufferedOutputStream;
82import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070083import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070085import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import java.io.FileOutputStream;
87import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070088import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010089import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070090import java.util.ArrayList;
91import java.util.List;
92
Fyodor Kupolov262f9952015-03-23 18:55:11 -070093import libcore.io.IoUtils;
94
Makoto Onuki068c54a2015-10-13 14:34:03 -070095/**
96 * Service for {@link UserManager}.
97 *
98 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -070099 * <ul>
100 * <li> Methods suffixed with "LILP" should be called within {@link #mInstallLock} and
101 * {@link #mPackagesLock} locks obtained in the respective order.
102 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
103 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
104 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700105 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700106public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700107 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki068c54a2015-10-13 14:34:03 -0700108 private static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700109
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700112 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700114 private static final String ATTR_CREATION_TIME = "created";
115 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700116 private static final String ATTR_SERIAL_NO = "serialNumber";
117 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700118 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700119 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700120 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100121 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700122 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530123 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800126 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800127 private static final String TAG_ENTRY = "entry";
128 private static final String TAG_VALUE = "value";
129 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700130 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800131 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700133 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
134 private static final String ATTR_TYPE_STRING = "s";
135 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700136 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700137 private static final String ATTR_TYPE_BUNDLE = "B";
138 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700139
Amith Yamasani0b285492011-04-14 17:35:23 -0700140 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700142 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100143 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800145 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700146 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800147
Amith Yamasani634cf312012-10-04 17:34:21 -0700148 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700149 // We need to keep process uid within Integer.MAX_VALUE.
150 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700151
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700152 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700153
Amith Yamasani920ace02012-09-20 22:15:37 -0700154 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
155
Nicolas Prevotb8186812015-08-06 15:00:03 +0100156 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700157 // without first making sure that the rest of the framework is prepared for it.
158 private static final int MAX_MANAGED_PROFILES = 1;
159
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800160 static final int WRITE_USER_MSG = 1;
161 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530162
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700163 private static final String XATTR_SERIAL = "user.serial";
164
Dianne Hackborn4428e172012-08-24 17:43:05 -0700165 private final Context mContext;
166 private final PackageManagerService mPm;
167 private final Object mInstallLock;
168 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700169 // Short-term lock for internal state, when interaction/sync with PM is not required
170 private final Object mUsersLock = new Object();
171 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700172
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800173 private final Handler mHandler;
174
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700175 private final File mUsersDir;
176 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700177
Fyodor Kupolov82402752015-10-28 14:54:51 -0700178 @GuardedBy("mUsersLock")
179 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700180
181 /**
182 * User restrictions set via UserManager. This doesn't include restrictions set by
183 * device owner / profile owners.
184 *
185 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
186 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
187 * maybe shared between {@link #mBaseUserRestrictions} and
188 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
189 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700190 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700191 */
192 @GuardedBy("mRestrictionsLock")
193 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
194
195 /**
196 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
197 * with device / profile owner restrictions. We'll initialize it lazily; use
198 * {@link #getEffectiveUserRestrictions} to access it.
199 *
200 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
201 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
202 * maybe shared between {@link #mBaseUserRestrictions} and
203 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
204 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700205 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700206 */
207 @GuardedBy("mRestrictionsLock")
208 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
209
Makoto Onuki4f160732015-10-27 17:15:38 -0700210 /**
Fyodor Kupolov82402752015-10-28 14:54:51 -0700211 * User restrictions that have already been applied in {@link #applyUserRestrictionsLR}. We
Makoto Onuki4f160732015-10-27 17:15:38 -0700212 * use it to detect restrictions that have changed since the last
Fyodor Kupolov82402752015-10-28 14:54:51 -0700213 * {@link #applyUserRestrictionsLR} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700214 */
215 @GuardedBy("mRestrictionsLock")
216 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
217
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530218 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800219
220 /**
221 * Set of user IDs being actively removed. Removed IDs linger in this set
222 * for several seconds to work around a VFS caching issue.
223 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700224 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800225 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700226
Fyodor Kupolov82402752015-10-28 14:54:51 -0700227 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700228 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700229 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700230 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700231
Jason Monk62062992014-05-06 09:55:28 -0400232 private IAppOpsService mAppOpsService;
233
Makoto Onuki068c54a2015-10-13 14:34:03 -0700234 private final LocalService mLocalService;
235
Makoto Onukid45a4a22015-11-02 17:17:38 -0800236 @GuardedBy("mUserRestrictionsListeners")
237 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
238 new ArrayList<>();
239
Amith Yamasani258848d2012-08-10 17:06:33 -0700240 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700241
Dianne Hackborn4428e172012-08-24 17:43:05 -0700242 public static UserManagerService getInstance() {
243 synchronized (UserManagerService.class) {
244 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700245 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700246 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700247
248 /**
249 * Available for testing purposes.
250 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700251 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700252 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700253 }
254
Dianne Hackborn4428e172012-08-24 17:43:05 -0700255 /**
256 * Called by package manager to create the service. This is closely
257 * associated with the package manager, and the given lock is the
258 * package manager's own lock.
259 */
260 UserManagerService(Context context, PackageManagerService pm,
261 Object installLock, Object packagesLock) {
262 this(context, pm, installLock, packagesLock,
263 Environment.getDataDirectory(),
264 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700265 }
266
Dianne Hackborn4428e172012-08-24 17:43:05 -0700267 /**
268 * Available for testing purposes.
269 */
270 private UserManagerService(Context context, PackageManagerService pm,
271 Object installLock, Object packagesLock,
272 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700273 mContext = context;
274 mPm = pm;
275 mInstallLock = installLock;
276 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800277 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700278 synchronized (mInstallLock) {
279 synchronized (mPackagesLock) {
280 mUsersDir = new File(dataDir, USER_INFO_DIR);
281 mUsersDir.mkdirs();
282 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700283 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700284 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700285 FileUtils.setPermissions(mUsersDir.toString(),
286 FileUtils.S_IRWXU|FileUtils.S_IRWXG
287 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
288 -1, -1);
289 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800290 initDefaultGuestRestrictions();
Fyodor Kupolov82402752015-10-28 14:54:51 -0700291 readUserListLILP();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700292 sInstance = this;
293 }
294 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700295 mLocalService = new LocalService();
296 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700297 }
298
299 void systemReady() {
300 synchronized (mInstallLock) {
301 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700302 synchronized (mUsersLock) {
303 // Prune out any partially created/partially removed users.
304 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
305 final int userSize = mUsers.size();
306 for (int i = 0; i < userSize; i++) {
307 UserInfo ui = mUsers.valueAt(i);
308 if ((ui.partial || ui.guestToRemove) && i != 0) {
309 partials.add(ui);
310 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700311 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700312 final int partialsSize = partials.size();
313 for (int i = 0; i < partialsSize; i++) {
314 UserInfo ui = partials.get(i);
315 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
316 + " (name=" + ui.name + ")");
317 removeUserStateLILP(ui.id);
318 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700319 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700320 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700321 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700322 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400323 mAppOpsService = IAppOpsService.Stub.asInterface(
324 ServiceManager.getService(Context.APP_OPS_SERVICE));
325 for (int i = 0; i < mUserIds.length; ++i) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700326 final int userId = mUserIds[i];
Jason Monk62062992014-05-06 09:55:28 -0400327 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700328 mAppOpsService.setUserRestrictions(getEffectiveUserRestrictions(userId), userId);
Jason Monk62062992014-05-06 09:55:28 -0400329 } catch (RemoteException e) {
330 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
331 }
332 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700333 }
334
335 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700336 public UserInfo getPrimaryUser() {
337 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700338 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700339 final int userSize = mUsers.size();
340 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700341 UserInfo ui = mUsers.valueAt(i);
342 if (ui.isPrimary()) {
343 return ui;
344 }
345 }
346 }
347 return null;
348 }
349
350 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700351 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700352 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700353 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700354 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700355 final int userSize = mUsers.size();
356 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700357 UserInfo ui = mUsers.valueAt(i);
358 if (ui.partial) {
359 continue;
360 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800361 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700362 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700363 }
Amith Yamasani13593602012-03-22 16:16:17 -0700364 }
365 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700366 }
Amith Yamasani13593602012-03-22 16:16:17 -0700367 }
368
Amith Yamasani258848d2012-08-10 17:06:33 -0700369 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100370 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800371 if (userId != UserHandle.getCallingUserId()) {
372 checkManageUsersPermission("getting profiles related to user " + userId);
373 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700374 final long ident = Binder.clearCallingIdentity();
375 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700376 synchronized (mUsersLock) {
377 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100378 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700379 } finally {
380 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000381 }
382 }
383
Amith Yamasanibe465322014-04-24 13:45:17 -0700384 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700385 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
386 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700387 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700388 if (user == null) {
389 // Probably a dying user
390 return users;
391 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700392 final int userSize = mUsers.size();
393 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700394 UserInfo profile = mUsers.valueAt(i);
395 if (!isProfileOf(user, profile)) {
396 continue;
397 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100398 if (enabledOnly && !profile.isEnabled()) {
399 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700400 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700401 if (mRemovingUserIds.get(profile.id)) {
402 continue;
403 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700404 users.add(profile);
405 }
406 return users;
407 }
408
Jessica Hummelbe81c802014-04-22 15:49:22 +0100409 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700410 public int getCredentialOwnerProfile(int userHandle) {
411 checkManageUsersPermission("get the credential owner");
Clara Bayarri965da392015-10-28 17:53:53 +0000412 if (!mContext.getSystemService(StorageManager.class).isPerUserEncryptionEnabled()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700413 synchronized (mUsersLock) {
414 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700415 if (profileParent != null) {
416 return profileParent.id;
417 }
418 }
419 }
420
421 return userHandle;
422 }
423
424 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700425 public boolean isSameProfileGroup(int userId, int otherUserId) {
426 if (userId == otherUserId) return true;
427 checkManageUsersPermission("check if in the same profile group");
428 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700429 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700430 }
431 }
432
Fyodor Kupolov82402752015-10-28 14:54:51 -0700433 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
434 synchronized (mUsersLock) {
435 UserInfo userInfo = getUserInfoLU(userId);
436 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
437 return false;
438 }
439 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
440 if (otherUserInfo == null
441 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
442 return false;
443 }
444 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700445 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700446 }
447
448 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100449 public UserInfo getProfileParent(int userHandle) {
450 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700451 synchronized (mUsersLock) {
452 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700453 }
454 }
455
Fyodor Kupolov82402752015-10-28 14:54:51 -0700456 private UserInfo getProfileParentLU(int userHandle) {
457 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700458 if (profile == null) {
459 return null;
460 }
461 int parentUserId = profile.profileGroupId;
462 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
463 return null;
464 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700465 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100466 }
467 }
468
Fyodor Kupolov82402752015-10-28 14:54:51 -0700469 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100470 return user.id == profile.id ||
471 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
472 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000473 }
474
475 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100476 public void setUserEnabled(int userId) {
477 checkManageUsersPermission("enable user");
478 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700479 UserInfo info;
480 synchronized (mUsersLock) {
481 info = getUserInfoLU(userId);
482 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100483 if (info != null && !info.isEnabled()) {
484 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700485 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100486 }
487 }
488 }
489
490 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700491 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700492 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700493 synchronized (mUsersLock) {
494 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700495 }
496 }
497
Amith Yamasani71e6c692013-03-24 17:39:28 -0700498 @Override
499 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700500 synchronized (mUsersLock) {
501 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700502 }
503 }
504
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700505 @Override
506 public boolean canHaveRestrictedProfile(int userId) {
507 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700508 synchronized (mUsersLock) {
509 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700510 if (userInfo == null || !userInfo.canHaveProfile()) {
511 return false;
512 }
513 if (!userInfo.isAdmin()) {
514 return false;
515 }
516 }
517 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
518 Context.DEVICE_POLICY_SERVICE);
519 // restricted profile can be created if there is no DO set and the admin user has no PO
520 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
521 }
522
Amith Yamasani195263742012-08-21 15:40:12 -0700523 /*
524 * Should be locked on mUsers before calling this.
525 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700526 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700527 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700528 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800529 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700530 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
531 return null;
532 }
533 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700534 }
535
Fyodor Kupolov82402752015-10-28 14:54:51 -0700536 /**
537 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
538 * <p>No permissions checking or any addition checks are made</p>
539 */
540 private UserInfo getUserInfoNoChecks(int userId) {
541 synchronized (mUsersLock) {
542 return mUsers.get(userId);
543 }
544 }
545
Amith Yamasani236b2b52015-08-18 14:32:14 -0700546 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700547 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700548 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700549 }
550
Amith Yamasani258848d2012-08-10 17:06:33 -0700551 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700552 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700553 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700554 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700555 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700556 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700557 if (info == null || info.partial) {
558 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
559 return;
560 }
Amith Yamasani13593602012-03-22 16:16:17 -0700561 if (name != null && !name.equals(info.name)) {
562 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700563 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700564 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700565 }
566 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700567 if (changed) {
568 sendUserInfoChangedBroadcast(userId);
569 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700570 }
571
Amith Yamasani258848d2012-08-10 17:06:33 -0700572 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700573 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700574 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400575 long ident = Binder.clearCallingIdentity();
576 try {
577 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700578 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400579 if (info == null || info.partial) {
580 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
581 return;
582 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700583 writeBitmapLP(info, bitmap);
584 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700585 }
Jason Monk9a944532014-07-08 09:31:21 -0400586 sendUserInfoChangedBroadcast(userId);
587 } finally {
588 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700589 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700590 }
591
592 private void sendUserInfoChangedBroadcast(int userId) {
593 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
594 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
595 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700596 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700597 }
598
Amith Yamasani258848d2012-08-10 17:06:33 -0700599 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100600 public ParcelFileDescriptor getUserIcon(int userId) {
601 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700602 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700603 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700604 if (info == null || info.partial) {
605 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
606 return null;
607 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700608 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100609 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
610 || callingGroupId != info.profileGroupId) {
611 checkManageUsersPermission("get the icon of a user who is not related");
612 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700613 if (info.iconPath == null) {
614 return null;
615 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100616 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700617 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100618
619 try {
620 return ParcelFileDescriptor.open(
621 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
622 } catch (FileNotFoundException e) {
623 Log.e(LOG_TAG, "Couldn't find icon file", e);
624 }
625 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700626 }
627
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700628 public void makeInitialized(int userId) {
629 checkManageUsersPermission("makeInitialized");
630 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700631 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700632 if (info == null || info.partial) {
633 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700634 // TODO Check if we should return here instead of a null check below
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700635 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700636 if (info != null && (info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700637 info.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -0800638 scheduleWriteUser(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700639 }
640 }
641 }
642
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700643 /**
644 * If default guest restrictions haven't been initialized yet, add the basic
645 * restrictions.
646 */
647 private void initDefaultGuestRestrictions() {
648 if (mGuestRestrictions.isEmpty()) {
649 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800650 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700651 }
652 }
653
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800654 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530655 public Bundle getDefaultGuestRestrictions() {
656 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700657 // TODO Switch to mGuestRestrictions for locking
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530658 synchronized (mPackagesLock) {
659 return new Bundle(mGuestRestrictions);
660 }
661 }
662
663 @Override
664 public void setDefaultGuestRestrictions(Bundle restrictions) {
665 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700666 synchronized (mInstallLock) {
667 synchronized (mPackagesLock) {
668 mGuestRestrictions.clear();
669 mGuestRestrictions.putAll(restrictions);
670 writeUserListLILP();
671 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530672 }
673 }
674
Makoto Onuki068c54a2015-10-13 14:34:03 -0700675 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700676 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700677 final DevicePolicyManagerInternal dpmi =
678 LocalServices.getService(DevicePolicyManagerInternal.class);
679 final Bundle systemRestrictions = mBaseUserRestrictions.get(userId);
680
681 final Bundle effective;
682 if (dpmi == null) {
683 // TODO Make sure it's because DPMS is disabled and not because we called it too early.
684 effective = systemRestrictions;
685 } else {
686 effective = dpmi.getComposedUserRestrictions(userId, systemRestrictions);
687 }
688 return effective;
689 }
690
691 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700692 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700693 if (DBG) {
694 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
695 }
696 mCachedEffectiveUserRestrictions.remove(userId);
697 }
698
699 private Bundle getEffectiveUserRestrictions(int userId) {
700 synchronized (mRestrictionsLock) {
701 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
702 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700703 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700704 mCachedEffectiveUserRestrictions.put(userId, restrictions);
705 }
706 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700707 }
708 }
709
Makoto Onuki068c54a2015-10-13 14:34:03 -0700710 /** @return a specific user restriction that's in effect currently. */
711 @Override
712 public boolean hasUserRestriction(String restrictionKey, int userId) {
713 Bundle restrictions = getEffectiveUserRestrictions(userId);
714 return restrictions != null && restrictions.getBoolean(restrictionKey);
715 }
716
717 /**
718 * @return UserRestrictions that are in effect currently. This always returns a new
719 * {@link Bundle}.
720 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700721 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800722 public Bundle getUserRestrictions(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700723 Bundle restrictions = getEffectiveUserRestrictions(userId);
724 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800725 }
726
727 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700728 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700729 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700730 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
731 setUserRestrictionNoCheck(key, value, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700732 }
733 }
734
735 @Override
736 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
737 checkSystemOrRoot("setSystemControlledUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700738 setUserRestrictionNoCheck(key, value, userId);
739 }
740
741 private void setUserRestrictionNoCheck(String key, boolean value, int userId) {
742 synchronized (mRestrictionsLock) {
743 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
744 // a copy.
745 final Bundle newRestrictions = new Bundle();
746 UserRestrictionsUtils.merge(newRestrictions, mBaseUserRestrictions.get(userId));
747 newRestrictions.putBoolean(key, value);
748
Fyodor Kupolov82402752015-10-28 14:54:51 -0700749 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700750 }
751 }
752
Makoto Onuki068c54a2015-10-13 14:34:03 -0700753 /**
754 * Optionally updating user restrictions, calculate the effective user restrictions by
755 * consulting {@link com.android.server.devicepolicy.DevicePolicyManagerService} and also
756 * apply it to {@link com.android.server.AppOpsService}.
757 * TODO applyUserRestrictionsLocked() should also apply to system settings.
758 *
759 * @param newRestrictions User restrictions to set. If null, only the effective restrictions
760 * will be updated. Note don't pass an existing Bundle in {@link #mBaseUserRestrictions}
761 * or {@link #mCachedEffectiveUserRestrictions}; that'll most likely cause a sub
762 * @param userId target user ID.
763 */
764 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700765 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700766 @Nullable Bundle newRestrictions, int userId) {
767 if (DBG) {
768 Log.d(LOG_TAG, "updateUserRestrictionsInternalLocked userId=" + userId
769 + " bundle=" + newRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800770 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700771 // Update system restrictions.
772 if (newRestrictions != null) {
773 // If newRestrictions == the current one, it's probably a bug.
774 Preconditions.checkState(mBaseUserRestrictions.get(userId) != newRestrictions);
775 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
776 != newRestrictions);
777 mBaseUserRestrictions.put(userId, newRestrictions);
Makoto Onuki9e935a32015-11-06 14:24:24 -0800778 scheduleWriteUser(mUsers.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700779 }
780
Fyodor Kupolov82402752015-10-28 14:54:51 -0700781 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700782
Makoto Onuki759a7632015-10-28 16:43:10 -0700783 mCachedEffectiveUserRestrictions.put(userId, effective);
784
Fyodor Kupolov82402752015-10-28 14:54:51 -0700785 applyUserRestrictionsLR(userId, effective);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800786 }
787
Makoto Onuki068c54a2015-10-13 14:34:03 -0700788 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700789 private void applyUserRestrictionsLR(int userId, Bundle newRestrictions) {
Makoto Onukid45a4a22015-11-02 17:17:38 -0800790 if (newRestrictions == null) {
791 newRestrictions = Bundle.EMPTY;
792 }
793
794 Bundle prevRestrictions = mAppliedUserRestrictions.get(userId);
795 if (prevRestrictions == null) {
796 prevRestrictions = Bundle.EMPTY;
797 }
Makoto Onuki4f160732015-10-27 17:15:38 -0700798
799 if (DBG) {
800 Log.d(LOG_TAG, "applyUserRestrictionsRL userId=" + userId
801 + " new=" + newRestrictions + " prev=" + prevRestrictions);
802 }
803
Makoto Onuki068c54a2015-10-13 14:34:03 -0700804 final long token = Binder.clearCallingIdentity();
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700805 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700806 mAppOpsService.setUserRestrictions(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700807 } catch (RemoteException e) {
808 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
809 } finally {
810 Binder.restoreCallingIdentity(token);
811 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700812
Makoto Onukid45a4a22015-11-02 17:17:38 -0800813 UserRestrictionsUtils.applyUserRestrictionsLR(
Makoto Onuki4f160732015-10-27 17:15:38 -0700814 mContext, userId, newRestrictions, prevRestrictions);
815
Makoto Onukid45a4a22015-11-02 17:17:38 -0800816 notifyUserRestrictionsListeners(userId, newRestrictions, prevRestrictions);
817
Makoto Onuki4f160732015-10-27 17:15:38 -0700818 mAppliedUserRestrictions.put(userId, new Bundle(newRestrictions));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700819 }
820
Makoto Onukid45a4a22015-11-02 17:17:38 -0800821 private void notifyUserRestrictionsListeners(final int userId,
822 Bundle newRestrictions, Bundle prevRestrictions) {
823
824 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
825 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
826
827 mHandler.post(new Runnable() {
828 @Override
829 public void run() {
830 final UserRestrictionsListener[] listeners;
831 synchronized (mUserRestrictionsListeners) {
832 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
833 mUserRestrictionsListeners.toArray(listeners);
834 }
835 for (int i = 0; i < listeners.length; i++) {
836 listeners[i].onUserRestrictionsChanged(userId,
837 newRestrictionsFinal, prevRestrictionsFinal);
838 }
839 }
840 });
841 }
842
Makoto Onuki068c54a2015-10-13 14:34:03 -0700843 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700844 private void updateEffectiveUserRestrictionsLR(int userId) {
845 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700846 }
847
848 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700849 private void updateEffectiveUserRestrictionsForAllUsersLR() {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700850 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700851 mCachedEffectiveUserRestrictions.clear();
852
Makoto Onuki068c54a2015-10-13 14:34:03 -0700853 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
854 // it on a handler.
855 final Runnable r = new Runnable() {
856 @Override
857 public void run() {
858 // Then get the list of running users.
859 final int[] runningUsers;
860 try {
861 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
862 } catch (RemoteException e) {
863 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
864 return;
865 }
866 // Then re-calculate the effective restrictions and apply, only for running users.
867 // It's okay if a new user has started after the getRunningUserIds() call,
868 // because we'll do the same thing (re-calculate the restrictions and apply)
869 // when we start a user.
870 // TODO: "Apply restrictions upon user start hasn't been implemented. Implement it.
871 synchronized (mRestrictionsLock) {
872 for (int i = 0; i < runningUsers.length; i++) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700873 updateUserRestrictionsInternalLR(null, runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700874 }
875 }
876 }
877 };
878 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700879 }
880
Amith Yamasani258848d2012-08-10 17:06:33 -0700881 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700882 * Check if we've hit the limit of how many users can be created.
883 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700884 private boolean isUserLimitReached() {
885 int count;
886 synchronized (mUsersLock) {
887 count = getAliveUsersExcludingGuestsCountLU();
888 }
889 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700890 }
891
892 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100893 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700894 checkManageUsersPermission("check if more managed profiles can be added.");
895 if (ActivityManager.isLowRamDeviceStatic()) {
896 return false;
897 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700898 if (!mContext.getPackageManager().hasSystemFeature(
899 PackageManager.FEATURE_MANAGED_USERS)) {
900 return false;
901 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100902 // Limit number of managed profiles that can be created
903 int managedProfilesCount = getProfiles(userId, true).size() - 1;
904 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
905 return false;
906 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700907 synchronized(mUsersLock) {
908 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100909 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700910 return false;
911 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700912 int usersCount = getAliveUsersExcludingGuestsCountLU();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700913 // We allow creating a managed profile in the special case where there is only one user.
914 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
915 }
916 }
917
Fyodor Kupolov82402752015-10-28 14:54:51 -0700918 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700919 int aliveUserCount = 0;
920 final int totalUserCount = mUsers.size();
921 // Skip over users being removed
922 for (int i = 0; i < totalUserCount; i++) {
923 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700924 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700925 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700926 aliveUserCount++;
927 }
928 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700929 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700930 }
931
932 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700933 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700934 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700935 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700936 *
937 * @param message used as message if SecurityException is thrown
938 * @throws SecurityException if the caller is not system or root
939 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700940 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700941 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700942 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400943 && ActivityManager.checkComponentPermission(
944 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700945 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
946 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
947 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400948 }
949
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700950 private static void checkSystemOrRoot(String message) {
951 final int uid = Binder.getCallingUid();
952 if (uid != Process.SYSTEM_UID && uid != 0) {
953 throw new SecurityException("Only system may call: " + message);
954 }
955 }
956
Fyodor Kupolov82402752015-10-28 14:54:51 -0700957 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700958 try {
959 File dir = new File(mUsersDir, Integer.toString(info.id));
960 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100961 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700962 if (!dir.exists()) {
963 dir.mkdir();
964 FileUtils.setPermissions(
965 dir.getPath(),
966 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
967 -1, -1);
968 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700969 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100970 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
971 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700972 info.iconPath = file.getAbsolutePath();
973 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700974 try {
975 os.close();
976 } catch (IOException ioe) {
977 // What the ... !
978 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100979 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700980 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700981 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700982 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700983 }
984
Amith Yamasani0b285492011-04-14 17:35:23 -0700985 /**
986 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
987 * cache it elsewhere.
988 * @return the array of user ids.
989 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700990 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700991 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700992 return mUserIds;
993 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700994 }
995
Fyodor Kupolov82402752015-10-28 14:54:51 -0700996 private void readUserListLILP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700997 if (!mUserListFile.exists()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700998 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700999 return;
1000 }
1001 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001002 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001003 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001004 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001005 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001006 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001007 int type;
1008 while ((type = parser.next()) != XmlPullParser.START_TAG
1009 && type != XmlPullParser.END_DOCUMENT) {
1010 ;
1011 }
1012
1013 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001014 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001015 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001016 return;
1017 }
1018
Amith Yamasani2a003292012-08-14 18:25:45 -07001019 mNextSerialNumber = -1;
1020 if (parser.getName().equals(TAG_USERS)) {
1021 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1022 if (lastSerialNumber != null) {
1023 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1024 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001025 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1026 if (versionNumber != null) {
1027 mUserVersion = Integer.parseInt(versionNumber);
1028 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001029 }
1030
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001031 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301032 if (type == XmlPullParser.START_TAG) {
1033 final String name = parser.getName();
1034 if (name.equals(TAG_USER)) {
1035 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001036 UserInfo user = readUserLILP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001037
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301038 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001039 synchronized (mUsersLock) {
1040 mUsers.put(user.id, user);
1041 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1042 mNextSerialNumber = user.id + 1;
1043 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301044 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001045 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301046 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001047 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1048 && type != XmlPullParser.END_TAG) {
1049 if (type == XmlPullParser.START_TAG) {
1050 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001051 UserRestrictionsUtils
1052 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001053 }
1054 break;
1055 }
1056 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001057 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001058 }
1059 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001060 updateUserIds();
1061 upgradeIfNecessaryLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001062 } catch (IOException ioe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001063 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001064 } catch (XmlPullParserException pe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001065 fallbackToSingleUserLILP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001066 } finally {
1067 if (fis != null) {
1068 try {
1069 fis.close();
1070 } catch (IOException e) {
1071 }
1072 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001073 }
1074 }
1075
Amith Yamasani6f34b412012-10-22 18:19:27 -07001076 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001077 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001078 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001079 private void upgradeIfNecessaryLILP() {
Amith Yamasani6f34b412012-10-22 18:19:27 -07001080 int userVersion = mUserVersion;
1081 if (userVersion < 1) {
1082 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001083 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001084 if ("Primary".equals(user.name)) {
1085 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001086 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001087 }
1088 userVersion = 1;
1089 }
1090
Amith Yamasanibc9625052012-11-15 14:39:18 -08001091 if (userVersion < 2) {
1092 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001093 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001094 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1095 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001096 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001097 }
1098 userVersion = 2;
1099 }
1100
Amith Yamasani350962c2013-08-06 11:18:53 -07001101
Amith Yamasani5e486f52013-08-07 11:06:44 -07001102 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001103 userVersion = 4;
1104 }
1105
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001106 if (userVersion < 5) {
1107 initDefaultGuestRestrictions();
1108 userVersion = 5;
1109 }
1110
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001111 if (userVersion < 6) {
1112 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001113 synchronized (mUsersLock) {
1114 for (int i = 0; i < mUsers.size(); i++) {
1115 UserInfo user = mUsers.valueAt(i);
1116 // In non-split mode, only user 0 can have restricted profiles
1117 if (!splitSystemUser && user.isRestricted()
1118 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1119 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001120 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001121 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001122 }
1123 }
1124 userVersion = 6;
1125 }
1126
Amith Yamasani6f34b412012-10-22 18:19:27 -07001127 if (userVersion < USER_VERSION) {
1128 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1129 + USER_VERSION);
1130 } else {
1131 mUserVersion = userVersion;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001132 writeUserListLILP();
Amith Yamasani6f34b412012-10-22 18:19:27 -07001133 }
1134 }
1135
Fyodor Kupolov82402752015-10-28 14:54:51 -07001136 private void fallbackToSingleUserLILP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001137 int flags = UserInfo.FLAG_INITIALIZED;
1138 // In split system user mode, the admin and primary flags are assigned to the first human
1139 // user.
1140 if (!UserManager.isSplitSystemUser()) {
1141 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1142 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001143 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001144 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001145 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001146 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001147 synchronized (mUsersLock) {
1148 mUsers.put(system.id, system);
1149 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001150 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001151 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001152
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001153 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001154 synchronized (mRestrictionsLock) {
1155 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1156 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001157
Fyodor Kupolov82402752015-10-28 14:54:51 -07001158 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001159 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001160
Fyodor Kupolov82402752015-10-28 14:54:51 -07001161 writeUserListLILP();
1162 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001163 }
1164
Makoto Onuki9e935a32015-11-06 14:24:24 -08001165 private void scheduleWriteUser(UserInfo userInfo) {
1166 // No need to wrap it within a lock -- worst case, we'll just post the same message
1167 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001168 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1169 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1170 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1171 }
1172 }
1173
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001174 /*
1175 * Writes the user file in this format:
1176 *
1177 * <user flags="20039023" id="0">
1178 * <name>Primary</name>
1179 * </user>
1180 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001181 private void writeUserLP(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001182 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001183 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001184 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001185 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001186 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1187
1188 // XmlSerializer serializer = XmlUtils.serializerInstance();
1189 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001190 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001191 serializer.startDocument(null, true);
1192 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1193
1194 serializer.startTag(null, TAG_USER);
1195 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001196 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001197 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001198 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1199 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1200 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001201 if (userInfo.iconPath != null) {
1202 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1203 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001204 if (userInfo.partial) {
1205 serializer.attribute(null, ATTR_PARTIAL, "true");
1206 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001207 if (userInfo.guestToRemove) {
1208 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1209 }
Kenny Guy2a764942014-04-02 13:29:20 +01001210 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1211 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1212 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001213 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001214 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1215 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1216 Integer.toString(userInfo.restrictedProfileParentId));
1217 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001218 serializer.startTag(null, TAG_NAME);
1219 serializer.text(userInfo.name);
1220 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001221 Bundle restrictions;
1222 synchronized (mRestrictionsLock) {
1223 restrictions = mBaseUserRestrictions.get(userInfo.id);
1224 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001225 if (restrictions != null) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001226 UserRestrictionsUtils
1227 .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001228 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001229 serializer.endTag(null, TAG_USER);
1230
1231 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001232 userFile.finishWrite(fos);
1233 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001234 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001235 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001236 }
1237 }
1238
1239 /*
1240 * Writes the user list file in this format:
1241 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001242 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001243 * <user id="0"></user>
1244 * <user id="2"></user>
1245 * </users>
1246 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001247 private void writeUserListLILP() {
1248 // TODO Investigate removing a dependency on mInstallLock
Amith Yamasani742a6712011-05-04 14:49:28 -07001249 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001250 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001251 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001252 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001253 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1254
1255 // XmlSerializer serializer = XmlUtils.serializerInstance();
1256 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001257 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001258 serializer.startDocument(null, true);
1259 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1260
1261 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001262 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001263 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001264
Adam Lesinskieddeb492014-09-08 17:50:03 -07001265 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001266 UserRestrictionsUtils
1267 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301268 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001269 int[] userIdsToWrite;
1270 synchronized (mUsersLock) {
1271 userIdsToWrite = new int[mUsers.size()];
1272 for (int i = 0; i < userIdsToWrite.length; i++) {
1273 UserInfo user = mUsers.valueAt(i);
1274 userIdsToWrite[i] = user.id;
1275 }
1276 }
1277 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001278 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001279 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001280 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001281 }
1282
1283 serializer.endTag(null, TAG_USERS);
1284
1285 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001286 userListFile.finishWrite(fos);
1287 } catch (Exception e) {
1288 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001289 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001290 }
1291 }
1292
Fyodor Kupolov82402752015-10-28 14:54:51 -07001293 private UserInfo readUserLILP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001294 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001295 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001296 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001297 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001298 long creationTime = 0L;
1299 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001300 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001301 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001302 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001303 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001304 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001305
1306 FileInputStream fis = null;
1307 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001308 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001309 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001310 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001311 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001312 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001313 int type;
1314 while ((type = parser.next()) != XmlPullParser.START_TAG
1315 && type != XmlPullParser.END_DOCUMENT) {
1316 ;
1317 }
1318
1319 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001320 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001321 return null;
1322 }
1323
1324 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001325 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1326 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001327 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001328 return null;
1329 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001330 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1331 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001332 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001333 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1334 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001335 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1336 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001337 restrictedProfileParentId = readIntAttribute(parser,
1338 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001339 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1340 if ("true".equals(valueString)) {
1341 partial = true;
1342 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001343 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1344 if ("true".equals(valueString)) {
1345 guestToRemove = true;
1346 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001347
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001348 int outerDepth = parser.getDepth();
1349 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1350 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1351 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1352 continue;
1353 }
1354 String tag = parser.getName();
1355 if (TAG_NAME.equals(tag)) {
1356 type = parser.next();
1357 if (type == XmlPullParser.TEXT) {
1358 name = parser.getText();
1359 }
1360 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001361 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001362 }
1363 }
1364 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001365
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001366 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001367 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001368 userInfo.creationTime = creationTime;
1369 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001370 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001371 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001372 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001373 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001374 synchronized (mRestrictionsLock) {
1375 mBaseUserRestrictions.append(id, restrictions);
1376 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001377 return userInfo;
1378
1379 } catch (IOException ioe) {
1380 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001381 } finally {
1382 if (fis != null) {
1383 try {
1384 fis.close();
1385 } catch (IOException e) {
1386 }
1387 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001388 }
1389 return null;
1390 }
1391
Amith Yamasani920ace02012-09-20 22:15:37 -07001392 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1393 String valueString = parser.getAttributeValue(null, attr);
1394 if (valueString == null) return defaultValue;
1395 try {
1396 return Integer.parseInt(valueString);
1397 } catch (NumberFormatException nfe) {
1398 return defaultValue;
1399 }
1400 }
1401
1402 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1403 String valueString = parser.getAttributeValue(null, attr);
1404 if (valueString == null) return defaultValue;
1405 try {
1406 return Long.parseLong(valueString);
1407 } catch (NumberFormatException nfe) {
1408 return defaultValue;
1409 }
1410 }
1411
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001412 private boolean isPackageInstalled(String pkg, int userId) {
1413 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1414 PackageManager.GET_UNINSTALLED_PACKAGES,
1415 userId);
1416 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1417 return false;
1418 }
1419 return true;
1420 }
1421
Amith Yamasanib82add22013-07-09 11:24:44 -07001422 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001423 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001424 * Does not do any permissions checking.
1425 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001426 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001427 synchronized (mPackagesLock) {
1428 File dir = Environment.getUserSystemDirectory(userId);
1429 String[] files = dir.list();
1430 if (files == null) return;
1431 for (String fileName : files) {
1432 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1433 File resFile = new File(dir, fileName);
1434 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001435 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001436 }
1437 }
1438 }
1439 }
1440 }
1441
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001442 /**
1443 * Removes the app restrictions file for a specific package and user id, if it exists.
1444 */
1445 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1446 synchronized (mPackagesLock) {
1447 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001448 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001449 if (resFile.exists()) {
1450 resFile.delete();
1451 }
1452 }
1453 }
1454
Kenny Guya52dc3e2014-02-11 15:33:14 +00001455 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001456 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001457 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001458 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001459 }
1460
Amith Yamasani258848d2012-08-10 17:06:33 -07001461 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001462 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001463 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001464 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001465 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001466
Jessica Hummelbe81c802014-04-22 15:49:22 +01001467 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001468 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1469 UserManager.DISALLOW_ADD_USER, false)) {
1470 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1471 return null;
1472 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001473 if (ActivityManager.isLowRamDeviceStatic()) {
1474 return null;
1475 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001476 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001477 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001478 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001479 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001480 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001481 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001482 try {
1483 synchronized (mInstallLock) {
1484 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001485 UserInfo parent = null;
1486 if (parentId != UserHandle.USER_NULL) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001487 synchronized (mUsersLock) {
1488 parent = getUserInfoLU(parentId);
1489 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001490 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001491 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001492 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1493 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001494 return null;
1495 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001496 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001497 // If we're not adding a guest user or a managed profile and the limit has
1498 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001499 return null;
1500 }
1501 // If we're adding a guest and there already exists one, bail.
Fyodor Kupolov82402752015-10-28 14:54:51 -07001502 if (isGuest && findCurrentGuestUser() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001503 return null;
1504 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001505 // In legacy mode, restricted profile's parent can only be the owner user
1506 if (isRestricted && !UserManager.isSplitSystemUser()
1507 && (parentId != UserHandle.USER_SYSTEM)) {
1508 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1509 return null;
1510 }
1511 if (isRestricted && UserManager.isSplitSystemUser()) {
1512 if (parent == null) {
1513 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1514 + "specified");
1515 return null;
1516 }
1517 if (!parent.canHaveProfile()) {
1518 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1519 + "created for the specified parent user id " + parentId);
1520 return null;
1521 }
1522 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001523 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001524 // And if there is no device owner, we also assign the admin flag to primary
1525 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001526 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001527 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001528 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001529 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1530 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1531 if (devicePolicyManager == null
1532 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001533 flags |= UserInfo.FLAG_ADMIN;
1534 }
1535 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001536 userId = getNextAvailableId();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001537 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001538 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001539 long now = System.currentTimeMillis();
1540 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001541 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001542 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001543 mUsers.put(userId, userInfo);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001544 writeUserListLILP();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001545 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001546 if (isManagedProfile) {
1547 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1548 parent.profileGroupId = parent.id;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001549 scheduleWriteUser(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001550 }
1551 userInfo.profileGroupId = parent.profileGroupId;
1552 } else if (isRestricted) {
1553 if (!parent.canHaveProfile()) {
1554 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1555 }
1556 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1557 parent.restrictedProfileParentId = parent.id;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001558 scheduleWriteUser(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001559 }
1560 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001561 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001562 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001563 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1564 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1565 final String volumeUuid = vol.getFsUuid();
1566 try {
1567 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1568 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001569 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001570 enforceSerialNumber(userDir, userInfo.serialNumber);
1571 } catch (IOException e) {
1572 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1573 }
1574 }
1575 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001576 userInfo.partial = false;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001577 scheduleWriteUser(userInfo);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001578 updateUserIds();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001579 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001580 synchronized (mRestrictionsLock) {
1581 mBaseUserRestrictions.append(userId, restrictions);
1582 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001583 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001584 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001585 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001586 if (userInfo != null) {
1587 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1588 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1589 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1590 android.Manifest.permission.MANAGE_USERS);
1591 }
1592 } finally {
1593 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001594 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001595 return userInfo;
1596 }
1597
Amith Yamasani0b285492011-04-14 17:35:23 -07001598 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001599 * @hide
1600 */
1601 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1602 checkManageUsersPermission("setupRestrictedProfile");
1603 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1604 if (user == null) {
1605 return null;
1606 }
1607 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1608 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1609 // the putIntForUser() will fail.
1610 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1611 android.provider.Settings.Secure.LOCATION_MODE,
1612 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1613 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1614 return user;
1615 }
1616
1617 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001618 * Find the current guest user. If the Guest user is partial,
1619 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001620 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001621 private UserInfo findCurrentGuestUser() {
1622 synchronized (mUsersLock) {
1623 final int size = mUsers.size();
1624 for (int i = 0; i < size; i++) {
1625 final UserInfo user = mUsers.valueAt(i);
1626 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1627 return user;
1628 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001629 }
1630 }
1631 return null;
1632 }
1633
1634 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001635 * Mark this guest user for deletion to allow us to create another guest
1636 * and switch to that user before actually removing this guest.
1637 * @param userHandle the userid of the current guest
1638 * @return whether the user could be marked for deletion
1639 */
1640 public boolean markGuestForDeletion(int userHandle) {
1641 checkManageUsersPermission("Only the system can remove users");
1642 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1643 UserManager.DISALLOW_REMOVE_USER, false)) {
1644 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1645 return false;
1646 }
1647
1648 long ident = Binder.clearCallingIdentity();
1649 try {
1650 final UserInfo user;
1651 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001652 synchronized (mUsersLock) {
1653 user = mUsers.get(userHandle);
1654 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1655 return false;
1656 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001657 }
1658 if (!user.isGuest()) {
1659 return false;
1660 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001661 // We set this to a guest user that is to be removed. This is a temporary state
1662 // where we are allowed to add new Guest users, even if this one is still not
1663 // removed. This user will still show up in getUserInfo() calls.
1664 // If we don't get around to removing this Guest user, it will be purged on next
1665 // startup.
1666 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001667 // Mark it as disabled, so that it isn't returned any more when
1668 // profiles are queried.
1669 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001670 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001671 }
1672 } finally {
1673 Binder.restoreCallingIdentity(ident);
1674 }
1675 return true;
1676 }
1677
1678 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001679 * Removes a user and all data directories created for that user. This method should be called
1680 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001681 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001682 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001683 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001684 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001685 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1686 UserManager.DISALLOW_REMOVE_USER, false)) {
1687 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1688 return false;
1689 }
1690
Kenny Guyee58b4f2014-05-23 15:19:53 +01001691 long ident = Binder.clearCallingIdentity();
1692 try {
1693 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001694 int currentUser = ActivityManager.getCurrentUser();
1695 if (currentUser == userHandle) {
1696 Log.w(LOG_TAG, "Current user cannot be removed");
1697 return false;
1698 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001699 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001700 synchronized (mUsersLock) {
1701 user = mUsers.get(userHandle);
1702 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1703 return false;
1704 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001705
Fyodor Kupolov82402752015-10-28 14:54:51 -07001706 // We remember deleted user IDs to prevent them from being
1707 // reused during the current boot; they can still be reused
1708 // after a reboot.
1709 mRemovingUserIds.put(userHandle, true);
1710 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001711
Kenny Guyee58b4f2014-05-23 15:19:53 +01001712 try {
1713 mAppOpsService.removeUser(userHandle);
1714 } catch (RemoteException e) {
1715 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1716 }
1717 // Set this to a partially created user, so that the user will be purged
1718 // on next startup, in case the runtime stops now before stopping and
1719 // removing the user completely.
1720 user.partial = true;
1721 // Mark it as disabled, so that it isn't returned any more when
1722 // profiles are queried.
1723 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001724 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001725 }
1726
1727 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1728 && user.isManagedProfile()) {
1729 // Send broadcast to notify system that the user removed was a
1730 // managed user.
1731 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1732 }
1733
1734 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1735 int res;
1736 try {
1737 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1738 new IStopUserCallback.Stub() {
1739 @Override
1740 public void userStopped(int userId) {
1741 finishRemoveUser(userId);
1742 }
1743 @Override
1744 public void userStopAborted(int userId) {
1745 }
1746 });
1747 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001748 return false;
1749 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001750 return res == ActivityManager.USER_OP_SUCCESS;
1751 } finally {
1752 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001753 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001754 }
1755
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001756 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001757 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001758 // Let other services shutdown any activity and clean up their state before completely
1759 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001760 long ident = Binder.clearCallingIdentity();
1761 try {
1762 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1763 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001764 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1765 android.Manifest.permission.MANAGE_USERS,
1766
1767 new BroadcastReceiver() {
1768 @Override
1769 public void onReceive(Context context, Intent intent) {
1770 if (DBG) {
1771 Slog.i(LOG_TAG,
1772 "USER_REMOVED broadcast sent, cleaning up user data "
1773 + userHandle);
1774 }
1775 new Thread() {
1776 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001777 // Clean up any ActivityManager state
1778 LocalServices.getService(ActivityManagerInternal.class)
1779 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001780 synchronized (mInstallLock) {
1781 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001782 removeUserStateLILP(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001783 }
1784 }
1785 }
1786 }.start();
1787 }
1788 },
1789
1790 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001791 } finally {
1792 Binder.restoreCallingIdentity(ident);
1793 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001794 }
1795
Fyodor Kupolov82402752015-10-28 14:54:51 -07001796 private void removeUserStateLILP(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001797 mContext.getSystemService(StorageManager.class)
1798 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001799 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001800 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001801
1802 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001803 synchronized (mUsersLock) {
1804 mUsers.remove(userHandle);
1805 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001806 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001807 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001808 userFile.delete();
1809 // Update the user list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001810 writeUserListLILP();
1811 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001812 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1813 }
1814
Amith Yamasani61f57372012-08-31 12:12:28 -07001815 private void removeDirectoryRecursive(File parent) {
1816 if (parent.isDirectory()) {
1817 String[] files = parent.list();
1818 for (String filename : files) {
1819 File child = new File(parent, filename);
1820 removeDirectoryRecursive(child);
1821 }
1822 }
1823 parent.delete();
1824 }
1825
Kenny Guyf8d3a232014-05-15 16:09:52 +01001826 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001827 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001828 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1829 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001830 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1831 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001832 }
1833
Amith Yamasani2a003292012-08-14 18:25:45 -07001834 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001835 public Bundle getApplicationRestrictions(String packageName) {
1836 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1837 }
1838
1839 @Override
1840 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001841 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001842 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001843 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001844 }
1845 synchronized (mPackagesLock) {
1846 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001847 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001848 }
1849 }
1850
1851 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001852 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001853 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001854 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001855 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001856 if (restrictions == null || restrictions.isEmpty()) {
1857 cleanAppRestrictionsForPackage(packageName, userId);
1858 } else {
1859 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001860 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001861 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001862 }
Robin Lee66e5d962014-04-09 16:44:21 +01001863
Kenny Guyd21b2182014-07-17 16:38:55 +01001864 if (isPackageInstalled(packageName, userId)) {
1865 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1866 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1867 changeIntent.setPackage(packageName);
1868 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1869 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1870 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001871 }
1872
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001873 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001874 mHandler.post(new Runnable() {
1875 @Override
1876 public void run() {
1877 List<ApplicationInfo> apps =
1878 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1879 userHandle).getList();
1880 final long ident = Binder.clearCallingIdentity();
1881 try {
1882 for (ApplicationInfo appInfo : apps) {
1883 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001884 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1885 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001886 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001887 userHandle);
1888 }
1889 }
1890 } finally {
1891 Binder.restoreCallingIdentity(ident);
1892 }
1893 }
1894 });
1895 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001896 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001897 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001898 try {
1899 return mContext.getPackageManager().getApplicationInfo(packageName,
1900 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1901 } catch (NameNotFoundException nnfe) {
1902 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001903 } finally {
1904 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001905 }
1906 }
1907
Fyodor Kupolov82402752015-10-28 14:54:51 -07001908 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001909 AtomicFile restrictionsFile =
1910 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1911 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001912 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001913 }
1914
1915 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001916 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001917 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001918 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001919 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001920 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001921 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001922
1923 FileInputStream fis = null;
1924 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001925 fis = restrictionsFile.openRead();
1926 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001927 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001928 XmlUtils.nextElement(parser);
1929 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001930 Slog.e(LOG_TAG, "Unable to read restrictions file "
1931 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001932 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001933 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001934 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1935 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001936 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001937 } catch (IOException|XmlPullParserException e) {
1938 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001939 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001940 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001941 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001942 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001943 }
1944
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001945 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1946 XmlPullParser parser) throws XmlPullParserException, IOException {
1947 int type = parser.getEventType();
1948 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1949 String key = parser.getAttributeValue(null, ATTR_KEY);
1950 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1951 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1952 if (multiple != null) {
1953 values.clear();
1954 int count = Integer.parseInt(multiple);
1955 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1956 if (type == XmlPullParser.START_TAG
1957 && parser.getName().equals(TAG_VALUE)) {
1958 values.add(parser.nextText().trim());
1959 count--;
1960 }
1961 }
1962 String [] valueStrings = new String[values.size()];
1963 values.toArray(valueStrings);
1964 restrictions.putStringArray(key, valueStrings);
1965 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1966 restrictions.putBundle(key, readBundleEntry(parser, values));
1967 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1968 final int outerDepth = parser.getDepth();
1969 ArrayList<Bundle> bundleList = new ArrayList<>();
1970 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1971 Bundle childBundle = readBundleEntry(parser, values);
1972 bundleList.add(childBundle);
1973 }
1974 restrictions.putParcelableArray(key,
1975 bundleList.toArray(new Bundle[bundleList.size()]));
1976 } else {
1977 String value = parser.nextText().trim();
1978 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1979 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1980 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1981 restrictions.putInt(key, Integer.parseInt(value));
1982 } else {
1983 restrictions.putString(key, value);
1984 }
1985 }
1986 }
1987 }
1988
1989 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1990 throws IOException, XmlPullParserException {
1991 Bundle childBundle = new Bundle();
1992 final int outerDepth = parser.getDepth();
1993 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1994 readEntry(childBundle, values, parser);
1995 }
1996 return childBundle;
1997 }
1998
Fyodor Kupolov82402752015-10-28 14:54:51 -07001999 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002000 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002001 AtomicFile restrictionsFile = new AtomicFile(
2002 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002003 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002004 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002005 }
2006
2007 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002008 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002009 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002010 try {
2011 fos = restrictionsFile.startWrite();
2012 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2013
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002014 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002015 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002016 serializer.startDocument(null, true);
2017 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2018
2019 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002020 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002021 serializer.endTag(null, TAG_RESTRICTIONS);
2022
2023 serializer.endDocument();
2024 restrictionsFile.finishWrite(fos);
2025 } catch (Exception e) {
2026 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002027 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2028 }
2029 }
2030
2031 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2032 throws IOException {
2033 for (String key : restrictions.keySet()) {
2034 Object value = restrictions.get(key);
2035 serializer.startTag(null, TAG_ENTRY);
2036 serializer.attribute(null, ATTR_KEY, key);
2037
2038 if (value instanceof Boolean) {
2039 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2040 serializer.text(value.toString());
2041 } else if (value instanceof Integer) {
2042 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2043 serializer.text(value.toString());
2044 } else if (value == null || value instanceof String) {
2045 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2046 serializer.text(value != null ? (String) value : "");
2047 } else if (value instanceof Bundle) {
2048 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2049 writeBundle((Bundle) value, serializer);
2050 } else if (value instanceof Parcelable[]) {
2051 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2052 Parcelable[] array = (Parcelable[]) value;
2053 for (Parcelable parcelable : array) {
2054 if (!(parcelable instanceof Bundle)) {
2055 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2056 }
2057 serializer.startTag(null, TAG_ENTRY);
2058 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2059 writeBundle((Bundle) parcelable, serializer);
2060 serializer.endTag(null, TAG_ENTRY);
2061 }
2062 } else {
2063 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2064 String[] values = (String[]) value;
2065 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2066 for (String choice : values) {
2067 serializer.startTag(null, TAG_VALUE);
2068 serializer.text(choice != null ? choice : "");
2069 serializer.endTag(null, TAG_VALUE);
2070 }
2071 }
2072 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002073 }
2074 }
2075
2076 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002077 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002078 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002079 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002080 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002081 }
2082 }
2083
2084 @Override
2085 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002086 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002087 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002088 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002089 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002090 }
2091 // Not found
2092 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002093 }
2094 }
2095
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002096 @Override
2097 public long getUserCreationTime(int userHandle) {
2098 int callingUserId = UserHandle.getCallingUserId();
2099 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002100 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002101 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002102 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002103 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002104 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002105 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002106 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002107 }
2108 }
2109 }
2110 if (userInfo == null) {
2111 throw new SecurityException("userHandle can only be the calling user or a managed "
2112 + "profile associated with this user");
2113 }
2114 return userInfo.creationTime;
2115 }
2116
Amith Yamasani0b285492011-04-14 17:35:23 -07002117 /**
2118 * Caches the list of user ids in an array, adjusting the array size when necessary.
2119 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002120 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002121 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002122 synchronized (mUsersLock) {
2123 final int userSize = mUsers.size();
2124 for (int i = 0; i < userSize; i++) {
2125 if (!mUsers.valueAt(i).partial) {
2126 num++;
2127 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002128 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002129 final int[] newUsers = new int[num];
2130 int n = 0;
2131 for (int i = 0; i < userSize; i++) {
2132 if (!mUsers.valueAt(i).partial) {
2133 newUsers[n++] = mUsers.keyAt(i);
2134 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002135 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002136 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002137 }
2138 }
2139
2140 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002141 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002142 * @param userId the user that was just foregrounded
2143 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002144 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002145 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002146 UserInfo user = getUserInfoNoChecks(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -07002147 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002148 if (user == null || user.partial) {
2149 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2150 return;
2151 }
2152 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002153 user.lastLoggedInTime = now;
Makoto Onuki9e935a32015-11-06 14:24:24 -08002154 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002155 }
2156 }
2157 }
2158
2159 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002160 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002161 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2162 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002163 * @return
2164 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002165 private int getNextAvailableId() {
2166 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002167 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002168 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002169 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002170 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002171 }
2172 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002173 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002174 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002175 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002176 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002177
Amith Yamasanifc95e702013-09-26 13:20:17 -07002178 private String packageToRestrictionsFileName(String packageName) {
2179 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2180 }
2181
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002182 /**
2183 * Create new {@code /data/user/[id]} directory and sets default
2184 * permissions.
2185 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002186 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2187 final StorageManager storage = context.getSystemService(StorageManager.class);
2188 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2189 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002190 }
2191
2192 /**
2193 * Enforce that serial number stored in user directory inode matches the
2194 * given expected value. Gracefully sets the serial number if currently
2195 * undefined.
2196 *
2197 * @throws IOException when problem extracting serial number, or serial
2198 * number is mismatched.
2199 */
2200 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2201 final int foundSerial = getSerialNumber(file);
2202 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2203
2204 if (foundSerial == -1) {
2205 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2206 try {
2207 setSerialNumber(file, serialNumber);
2208 } catch (IOException e) {
2209 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2210 }
2211
2212 } else if (foundSerial != serialNumber) {
2213 throw new IOException("Found serial number " + foundSerial
2214 + " doesn't match expected " + serialNumber);
2215 }
2216 }
2217
2218 /**
2219 * Set serial number stored in user directory inode.
2220 *
2221 * @throws IOException if serial number was already set
2222 */
2223 private static void setSerialNumber(File file, int serialNumber)
2224 throws IOException {
2225 try {
2226 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2227 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2228 } catch (ErrnoException e) {
2229 throw e.rethrowAsIOException();
2230 }
2231 }
2232
2233 /**
2234 * Return serial number stored in user directory inode.
2235 *
2236 * @return parsed serial number, or -1 if not set
2237 */
2238 private static int getSerialNumber(File file) throws IOException {
2239 try {
2240 final byte[] buf = new byte[256];
2241 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2242 final String serial = new String(buf, 0, len);
2243 try {
2244 return Integer.parseInt(serial);
2245 } catch (NumberFormatException e) {
2246 throw new IOException("Bad serial number: " + serial);
2247 }
2248 } catch (ErrnoException e) {
2249 if (e.errno == OsConstants.ENODATA) {
2250 return -1;
2251 } else {
2252 throw e.rethrowAsIOException();
2253 }
2254 }
2255 }
2256
Amith Yamasani920ace02012-09-20 22:15:37 -07002257 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002258 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2259 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2260 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2261 }
2262
2263 int onShellCommand(Shell shell, String cmd) {
2264 if (cmd == null) {
2265 return shell.handleDefaultCommands(cmd);
2266 }
2267
2268 final PrintWriter pw = shell.getOutPrintWriter();
2269 try {
2270 switch(cmd) {
2271 case "list":
2272 return runList(pw);
2273 }
2274 } catch (RemoteException e) {
2275 pw.println("Remote exception: " + e);
2276 }
2277 return -1;
2278 }
2279
2280 private int runList(PrintWriter pw) throws RemoteException {
2281 final IActivityManager am = ActivityManagerNative.getDefault();
2282 final List<UserInfo> users = getUsers(false);
2283 if (users == null) {
2284 pw.println("Error: couldn't get users");
2285 return 1;
2286 } else {
2287 pw.println("Users:");
2288 for (int i = 0; i < users.size(); i++) {
2289 String running = am.isUserRunning(users.get(i).id, false) ? " running" : "";
2290 pw.println("\t" + users.get(i).toString() + running);
2291 }
2292 return 0;
2293 }
2294 }
2295
2296 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002297 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2298 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2299 != PackageManager.PERMISSION_GRANTED) {
2300 pw.println("Permission Denial: can't dump UserManager from from pid="
2301 + Binder.getCallingPid()
2302 + ", uid=" + Binder.getCallingUid()
2303 + " without permission "
2304 + android.Manifest.permission.DUMP);
2305 return;
2306 }
2307
2308 long now = System.currentTimeMillis();
2309 StringBuilder sb = new StringBuilder();
2310 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002311 synchronized (mUsersLock) {
2312 pw.println("Users:");
2313 for (int i = 0; i < mUsers.size(); i++) {
2314 UserInfo user = mUsers.valueAt(i);
2315 if (user == null) {
2316 continue;
2317 }
2318 pw.print(" "); pw.print(user);
2319 pw.print(" serialNo="); pw.print(user.serialNumber);
2320 if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2321 pw.print(" <removing> ");
2322 }
2323 if (user.partial) {
2324 pw.print(" <partial>");
2325 }
2326 pw.println();
2327 pw.print(" Created: ");
2328 if (user.creationTime == 0) {
2329 pw.println("<unknown>");
2330 } else {
2331 sb.setLength(0);
2332 TimeUtils.formatDuration(now - user.creationTime, sb);
2333 sb.append(" ago");
2334 pw.println(sb);
2335 }
2336 pw.print(" Last logged in: ");
2337 if (user.lastLoggedInTime == 0) {
2338 pw.println("<unknown>");
2339 } else {
2340 sb.setLength(0);
2341 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2342 sb.append(" ago");
2343 pw.println(sb);
2344 }
2345 pw.println(" Restrictions:");
2346 synchronized (mRestrictionsLock) {
2347 UserRestrictionsUtils.dumpRestrictions(
2348 pw, " ", mBaseUserRestrictions.get(user.id));
2349 pw.println(" Effective restrictions:");
2350 UserRestrictionsUtils.dumpRestrictions(
2351 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2352 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002353 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002354 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002355 pw.println();
2356 pw.println("Guest restrictions:");
2357 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002358 }
2359 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002360
2361 final class MainHandler extends Handler {
2362
2363 @Override
2364 public void handleMessage(Message msg) {
2365 switch (msg.what) {
2366 case WRITE_USER_MSG:
2367 removeMessages(WRITE_USER_MSG, msg.obj);
2368 synchronized (mPackagesLock) {
2369 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002370 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002371 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002372 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002373 }
2374 }
2375 }
2376 }
2377 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002378
2379 /**
2380 * @param userId
2381 * @return whether the user has been initialized yet
2382 */
2383 boolean isInitialized(int userId) {
2384 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2385 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002386
2387 private class LocalService extends UserManagerInternal {
2388
2389 @Override
2390 public Object getUserRestrictionsLock() {
2391 return mRestrictionsLock;
2392 }
2393
2394 @Override
2395 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002396 public void updateEffectiveUserRestrictionsLR(int userId) {
2397 UserManagerService.this.updateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002398 }
2399
2400 @Override
2401 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002402 public void updateEffectiveUserRestrictionsForAllUsersLR() {
2403 UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersLR();
Makoto Onuki068c54a2015-10-13 14:34:03 -07002404 }
2405
2406 @Override
2407 public Bundle getBaseUserRestrictions(int userId) {
2408 synchronized (mRestrictionsLock) {
2409 return mBaseUserRestrictions.get(userId);
2410 }
2411 }
2412
2413 @Override
2414 public void setBaseUserRestrictionsByDpmsForMigration(
2415 int userId, Bundle baseRestrictions) {
2416 synchronized (mRestrictionsLock) {
2417 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002418 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002419 }
2420
Fyodor Kupolov82402752015-10-28 14:54:51 -07002421 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002422 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002423 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002424 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002425 } else {
2426 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2427 }
2428 }
2429 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002430
2431 @Override
2432 public boolean getUserRestriction(int userId, String key) {
2433 return getUserRestrictions(userId).getBoolean(key);
2434 }
2435
2436 @Override
2437 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2438 synchronized (mUserRestrictionsListeners) {
2439 mUserRestrictionsListeners.add(listener);
2440 }
2441 }
2442
2443 @Override
2444 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2445 synchronized (mUserRestrictionsListeners) {
2446 mUserRestrictionsListeners.remove(listener);
2447 }
2448 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002449 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002450
2451 private class Shell extends ShellCommand {
2452 @Override
2453 public int onCommand(String cmd) {
2454 return onShellCommand(this, cmd);
2455 }
2456
2457 @Override
2458 public void onHelp() {
2459 final PrintWriter pw = getOutPrintWriter();
2460 pw.println("User manager (user) commands:");
2461 pw.println(" help");
2462 pw.println(" Print this help text.");
2463 pw.println("");
2464 pw.println(" list");
2465 pw.println(" Prints all users on the system.");
2466 }
2467 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002468}