blob: 53ce9e269d4a4813a9adda8abd6488627c817691 [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>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800100 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700101 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
102 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
103 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700104 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700105public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700106 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki068c54a2015-10-13 14:34:03 -0700107 private static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700108
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700111 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700113 private static final String ATTR_CREATION_TIME = "created";
114 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700115 private static final String ATTR_SERIAL_NO = "serialNumber";
116 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700117 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700118 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700119 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100120 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700121 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530122 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800125 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800126 private static final String TAG_ENTRY = "entry";
127 private static final String TAG_VALUE = "value";
128 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700129 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800130 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700131
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700132 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
133 private static final String ATTR_TYPE_STRING = "s";
134 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700135 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700136 private static final String ATTR_TYPE_BUNDLE = "B";
137 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700138
Amith Yamasani0b285492011-04-14 17:35:23 -0700139 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700140 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700141 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100142 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800144 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700145 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800146
Amith Yamasani634cf312012-10-04 17:34:21 -0700147 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700148 // We need to keep process uid within Integer.MAX_VALUE.
149 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700150
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700151 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700152
Amith Yamasani920ace02012-09-20 22:15:37 -0700153 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
154
Nicolas Prevotb8186812015-08-06 15:00:03 +0100155 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700156 // without first making sure that the rest of the framework is prepared for it.
157 private static final int MAX_MANAGED_PROFILES = 1;
158
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800159 static final int WRITE_USER_MSG = 1;
160 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530161
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700162 private static final String XATTR_SERIAL = "user.serial";
163
Dianne Hackborn4428e172012-08-24 17:43:05 -0700164 private final Context mContext;
165 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700166 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700167 // Short-term lock for internal state, when interaction/sync with PM is not required
168 private final Object mUsersLock = new Object();
169 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700170
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800171 private final Handler mHandler;
172
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700173 private final File mUsersDir;
174 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700175
Fyodor Kupolov82402752015-10-28 14:54:51 -0700176 @GuardedBy("mUsersLock")
177 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700178
179 /**
180 * User restrictions set via UserManager. This doesn't include restrictions set by
181 * device owner / profile owners.
182 *
183 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
184 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
185 * maybe shared between {@link #mBaseUserRestrictions} and
186 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
187 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700188 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700189 */
190 @GuardedBy("mRestrictionsLock")
191 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
192
193 /**
194 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
195 * with device / profile owner restrictions. We'll initialize it lazily; use
196 * {@link #getEffectiveUserRestrictions} to access it.
197 *
198 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
199 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
200 * maybe shared between {@link #mBaseUserRestrictions} and
201 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
202 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700203 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700204 */
205 @GuardedBy("mRestrictionsLock")
206 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
207
Makoto Onuki4f160732015-10-27 17:15:38 -0700208 /**
Fyodor Kupolov82402752015-10-28 14:54:51 -0700209 * User restrictions that have already been applied in {@link #applyUserRestrictionsLR}. We
Makoto Onuki4f160732015-10-27 17:15:38 -0700210 * use it to detect restrictions that have changed since the last
Fyodor Kupolov82402752015-10-28 14:54:51 -0700211 * {@link #applyUserRestrictionsLR} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700212 */
213 @GuardedBy("mRestrictionsLock")
214 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
215
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800216 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530217 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800218
219 /**
220 * Set of user IDs being actively removed. Removed IDs linger in this set
221 * for several seconds to work around a VFS caching issue.
222 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700223 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800224 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700225
Fyodor Kupolov82402752015-10-28 14:54:51 -0700226 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700227 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800228 @GuardedBy("mPackagesLock")
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
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800248 @VisibleForTesting
249 UserManagerService(File dataDir) {
250 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700251 }
252
Dianne Hackborn4428e172012-08-24 17:43:05 -0700253 /**
254 * Called by package manager to create the service. This is closely
255 * associated with the package manager, and the given lock is the
256 * package manager's own lock.
257 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800258 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
259 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700260 }
261
Dianne Hackborn4428e172012-08-24 17:43:05 -0700262 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800263 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700264 mContext = context;
265 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700266 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800267 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800268 synchronized (mPackagesLock) {
269 mUsersDir = new File(dataDir, USER_INFO_DIR);
270 mUsersDir.mkdirs();
271 // Make zeroth user directory, for services to migrate their files to that location
272 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
273 userZeroDir.mkdirs();
274 FileUtils.setPermissions(mUsersDir.toString(),
275 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
276 -1, -1);
277 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
278 initDefaultGuestRestrictions();
279 readUserListLP();
280 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700281 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700282 mLocalService = new LocalService();
283 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700284 }
285
286 void systemReady() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800287 // Prune out any partially created/partially removed users.
288 ArrayList<UserInfo> partials = new ArrayList<>();
289 synchronized (mUsersLock) {
290 final int userSize = mUsers.size();
291 for (int i = 0; i < userSize; i++) {
292 UserInfo ui = mUsers.valueAt(i);
293 if ((ui.partial || ui.guestToRemove) && i != 0) {
294 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700295 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700296 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700297 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800298 final int partialsSize = partials.size();
299 for (int i = 0; i < partialsSize; i++) {
300 UserInfo ui = partials.get(i);
301 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
302 + " (name=" + ui.name + ")");
303 removeUserState(ui.id);
304 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700305 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400306 mAppOpsService = IAppOpsService.Stub.asInterface(
307 ServiceManager.getService(Context.APP_OPS_SERVICE));
308 for (int i = 0; i < mUserIds.length; ++i) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700309 final int userId = mUserIds[i];
Jason Monk62062992014-05-06 09:55:28 -0400310 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700311 mAppOpsService.setUserRestrictions(getEffectiveUserRestrictions(userId), userId);
Jason Monk62062992014-05-06 09:55:28 -0400312 } catch (RemoteException e) {
313 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
314 }
315 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700316 }
317
318 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700319 public UserInfo getPrimaryUser() {
320 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700321 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700322 final int userSize = mUsers.size();
323 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700324 UserInfo ui = mUsers.valueAt(i);
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800325 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700326 return ui;
327 }
328 }
329 }
330 return null;
331 }
332
333 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700334 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700335 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700336 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700337 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700338 final int userSize = mUsers.size();
339 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700340 UserInfo ui = mUsers.valueAt(i);
341 if (ui.partial) {
342 continue;
343 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800344 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700345 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700346 }
Amith Yamasani13593602012-03-22 16:16:17 -0700347 }
348 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700349 }
Amith Yamasani13593602012-03-22 16:16:17 -0700350 }
351
Amith Yamasani258848d2012-08-10 17:06:33 -0700352 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100353 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800354 if (userId != UserHandle.getCallingUserId()) {
355 checkManageUsersPermission("getting profiles related to user " + userId);
356 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700357 final long ident = Binder.clearCallingIdentity();
358 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700359 synchronized (mUsersLock) {
360 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100361 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700362 } finally {
363 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000364 }
365 }
366
Amith Yamasanibe465322014-04-24 13:45:17 -0700367 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700368 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
369 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700370 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700371 if (user == null) {
372 // Probably a dying user
373 return users;
374 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700375 final int userSize = mUsers.size();
376 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700377 UserInfo profile = mUsers.valueAt(i);
378 if (!isProfileOf(user, profile)) {
379 continue;
380 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100381 if (enabledOnly && !profile.isEnabled()) {
382 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700383 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700384 if (mRemovingUserIds.get(profile.id)) {
385 continue;
386 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700387 users.add(profile);
388 }
389 return users;
390 }
391
Jessica Hummelbe81c802014-04-22 15:49:22 +0100392 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700393 public int getCredentialOwnerProfile(int userHandle) {
394 checkManageUsersPermission("get the credential owner");
Clara Bayarri965da392015-10-28 17:53:53 +0000395 if (!mContext.getSystemService(StorageManager.class).isPerUserEncryptionEnabled()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700396 synchronized (mUsersLock) {
397 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700398 if (profileParent != null) {
399 return profileParent.id;
400 }
401 }
402 }
403
404 return userHandle;
405 }
406
407 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700408 public boolean isSameProfileGroup(int userId, int otherUserId) {
409 if (userId == otherUserId) return true;
410 checkManageUsersPermission("check if in the same profile group");
411 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700412 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700413 }
414 }
415
Fyodor Kupolov82402752015-10-28 14:54:51 -0700416 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
417 synchronized (mUsersLock) {
418 UserInfo userInfo = getUserInfoLU(userId);
419 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
420 return false;
421 }
422 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
423 if (otherUserInfo == null
424 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
425 return false;
426 }
427 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700428 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700429 }
430
431 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100432 public UserInfo getProfileParent(int userHandle) {
433 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700434 synchronized (mUsersLock) {
435 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700436 }
437 }
438
Fyodor Kupolov82402752015-10-28 14:54:51 -0700439 private UserInfo getProfileParentLU(int userHandle) {
440 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700441 if (profile == null) {
442 return null;
443 }
444 int parentUserId = profile.profileGroupId;
445 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
446 return null;
447 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700448 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100449 }
450 }
451
Fyodor Kupolov82402752015-10-28 14:54:51 -0700452 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100453 return user.id == profile.id ||
454 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
455 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000456 }
457
458 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100459 public void setUserEnabled(int userId) {
460 checkManageUsersPermission("enable user");
461 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700462 UserInfo info;
463 synchronized (mUsersLock) {
464 info = getUserInfoLU(userId);
465 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100466 if (info != null && !info.isEnabled()) {
467 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700468 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100469 }
470 }
471 }
472
473 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700474 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700475 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700476 synchronized (mUsersLock) {
477 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700478 }
479 }
480
Amith Yamasani71e6c692013-03-24 17:39:28 -0700481 @Override
482 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700483 synchronized (mUsersLock) {
484 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700485 }
486 }
487
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700488 @Override
489 public boolean canHaveRestrictedProfile(int userId) {
490 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700491 synchronized (mUsersLock) {
492 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700493 if (userInfo == null || !userInfo.canHaveProfile()) {
494 return false;
495 }
496 if (!userInfo.isAdmin()) {
497 return false;
498 }
499 }
500 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
501 Context.DEVICE_POLICY_SERVICE);
502 // restricted profile can be created if there is no DO set and the admin user has no PO
503 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
504 }
505
Amith Yamasani195263742012-08-21 15:40:12 -0700506 /*
507 * Should be locked on mUsers before calling this.
508 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700509 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700510 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700511 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800512 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700513 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
514 return null;
515 }
516 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700517 }
518
Fyodor Kupolov82402752015-10-28 14:54:51 -0700519 /**
520 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
521 * <p>No permissions checking or any addition checks are made</p>
522 */
523 private UserInfo getUserInfoNoChecks(int userId) {
524 synchronized (mUsersLock) {
525 return mUsers.get(userId);
526 }
527 }
528
Amith Yamasani236b2b52015-08-18 14:32:14 -0700529 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700530 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700531 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700532 }
533
Amith Yamasani258848d2012-08-10 17:06:33 -0700534 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700535 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700536 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700537 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700538 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700539 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700540 if (info == null || info.partial) {
541 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
542 return;
543 }
Amith Yamasani13593602012-03-22 16:16:17 -0700544 if (name != null && !name.equals(info.name)) {
545 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700546 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700547 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700548 }
549 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700550 if (changed) {
551 sendUserInfoChangedBroadcast(userId);
552 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700553 }
554
Amith Yamasani258848d2012-08-10 17:06:33 -0700555 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700556 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700557 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400558 long ident = Binder.clearCallingIdentity();
559 try {
560 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700561 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400562 if (info == null || info.partial) {
563 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
564 return;
565 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700566 writeBitmapLP(info, bitmap);
567 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700568 }
Jason Monk9a944532014-07-08 09:31:21 -0400569 sendUserInfoChangedBroadcast(userId);
570 } finally {
571 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700572 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700573 }
574
575 private void sendUserInfoChangedBroadcast(int userId) {
576 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
577 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
578 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700579 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700580 }
581
Amith Yamasani258848d2012-08-10 17:06:33 -0700582 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100583 public ParcelFileDescriptor getUserIcon(int userId) {
584 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700585 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700586 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700587 if (info == null || info.partial) {
588 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
589 return null;
590 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700591 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100592 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
593 || callingGroupId != info.profileGroupId) {
594 checkManageUsersPermission("get the icon of a user who is not related");
595 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700596 if (info.iconPath == null) {
597 return null;
598 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100599 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700600 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100601
602 try {
603 return ParcelFileDescriptor.open(
604 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
605 } catch (FileNotFoundException e) {
606 Log.e(LOG_TAG, "Couldn't find icon file", e);
607 }
608 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700609 }
610
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700611 public void makeInitialized(int userId) {
612 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800613 boolean scheduleWriteUser = false;
614 UserInfo info;
615 synchronized (mUsersLock) {
616 info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700617 if (info == null || info.partial) {
618 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800619 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700620 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800621 if ((info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700622 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800623 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700624 }
625 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800626 if (scheduleWriteUser) {
627 scheduleWriteUser(info);
628 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700629 }
630
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700631 /**
632 * If default guest restrictions haven't been initialized yet, add the basic
633 * restrictions.
634 */
635 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800636 synchronized (mGuestRestrictions) {
637 if (mGuestRestrictions.isEmpty()) {
638 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
639 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
640 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700641 }
642 }
643
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800644 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530645 public Bundle getDefaultGuestRestrictions() {
646 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800647 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530648 return new Bundle(mGuestRestrictions);
649 }
650 }
651
652 @Override
653 public void setDefaultGuestRestrictions(Bundle restrictions) {
654 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800655 synchronized (mGuestRestrictions) {
656 mGuestRestrictions.clear();
657 mGuestRestrictions.putAll(restrictions);
658 }
659 synchronized (mPackagesLock) {
660 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530661 }
662 }
663
Makoto Onuki068c54a2015-10-13 14:34:03 -0700664 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700665 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700666 final DevicePolicyManagerInternal dpmi =
667 LocalServices.getService(DevicePolicyManagerInternal.class);
668 final Bundle systemRestrictions = mBaseUserRestrictions.get(userId);
669
670 final Bundle effective;
671 if (dpmi == null) {
672 // TODO Make sure it's because DPMS is disabled and not because we called it too early.
673 effective = systemRestrictions;
674 } else {
675 effective = dpmi.getComposedUserRestrictions(userId, systemRestrictions);
676 }
677 return effective;
678 }
679
680 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700681 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700682 if (DBG) {
683 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
684 }
685 mCachedEffectiveUserRestrictions.remove(userId);
686 }
687
688 private Bundle getEffectiveUserRestrictions(int userId) {
689 synchronized (mRestrictionsLock) {
690 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
691 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700692 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700693 mCachedEffectiveUserRestrictions.put(userId, restrictions);
694 }
695 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700696 }
697 }
698
Makoto Onuki068c54a2015-10-13 14:34:03 -0700699 /** @return a specific user restriction that's in effect currently. */
700 @Override
701 public boolean hasUserRestriction(String restrictionKey, int userId) {
702 Bundle restrictions = getEffectiveUserRestrictions(userId);
703 return restrictions != null && restrictions.getBoolean(restrictionKey);
704 }
705
706 /**
707 * @return UserRestrictions that are in effect currently. This always returns a new
708 * {@link Bundle}.
709 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700710 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800711 public Bundle getUserRestrictions(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700712 Bundle restrictions = getEffectiveUserRestrictions(userId);
713 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800714 }
715
716 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700717 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700718 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700719 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
720 setUserRestrictionNoCheck(key, value, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700721 }
722 }
723
724 @Override
725 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
726 checkSystemOrRoot("setSystemControlledUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700727 setUserRestrictionNoCheck(key, value, userId);
728 }
729
730 private void setUserRestrictionNoCheck(String key, boolean value, int userId) {
731 synchronized (mRestrictionsLock) {
732 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
733 // a copy.
734 final Bundle newRestrictions = new Bundle();
735 UserRestrictionsUtils.merge(newRestrictions, mBaseUserRestrictions.get(userId));
736 newRestrictions.putBoolean(key, value);
737
Fyodor Kupolov82402752015-10-28 14:54:51 -0700738 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700739 }
740 }
741
Makoto Onuki068c54a2015-10-13 14:34:03 -0700742 /**
743 * Optionally updating user restrictions, calculate the effective user restrictions by
744 * consulting {@link com.android.server.devicepolicy.DevicePolicyManagerService} and also
745 * apply it to {@link com.android.server.AppOpsService}.
746 * TODO applyUserRestrictionsLocked() should also apply to system settings.
747 *
748 * @param newRestrictions User restrictions to set. If null, only the effective restrictions
749 * will be updated. Note don't pass an existing Bundle in {@link #mBaseUserRestrictions}
750 * or {@link #mCachedEffectiveUserRestrictions}; that'll most likely cause a sub
751 * @param userId target user ID.
752 */
753 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700754 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700755 @Nullable Bundle newRestrictions, int userId) {
756 if (DBG) {
757 Log.d(LOG_TAG, "updateUserRestrictionsInternalLocked userId=" + userId
758 + " bundle=" + newRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800759 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700760 // Update system restrictions.
761 if (newRestrictions != null) {
762 // If newRestrictions == the current one, it's probably a bug.
763 Preconditions.checkState(mBaseUserRestrictions.get(userId) != newRestrictions);
764 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
765 != newRestrictions);
766 mBaseUserRestrictions.put(userId, newRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800767 scheduleWriteUser(getUserInfoNoChecks(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700768 }
769
Fyodor Kupolov82402752015-10-28 14:54:51 -0700770 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700771
Makoto Onuki759a7632015-10-28 16:43:10 -0700772 mCachedEffectiveUserRestrictions.put(userId, effective);
773
Fyodor Kupolov82402752015-10-28 14:54:51 -0700774 applyUserRestrictionsLR(userId, effective);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800775 }
776
Makoto Onuki068c54a2015-10-13 14:34:03 -0700777 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700778 private void applyUserRestrictionsLR(int userId, Bundle newRestrictions) {
Makoto Onukid45a4a22015-11-02 17:17:38 -0800779 if (newRestrictions == null) {
780 newRestrictions = Bundle.EMPTY;
781 }
782
783 Bundle prevRestrictions = mAppliedUserRestrictions.get(userId);
784 if (prevRestrictions == null) {
785 prevRestrictions = Bundle.EMPTY;
786 }
Makoto Onuki4f160732015-10-27 17:15:38 -0700787
788 if (DBG) {
789 Log.d(LOG_TAG, "applyUserRestrictionsRL userId=" + userId
790 + " new=" + newRestrictions + " prev=" + prevRestrictions);
791 }
792
Makoto Onuki068c54a2015-10-13 14:34:03 -0700793 final long token = Binder.clearCallingIdentity();
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700794 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700795 mAppOpsService.setUserRestrictions(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700796 } catch (RemoteException e) {
797 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
798 } finally {
799 Binder.restoreCallingIdentity(token);
800 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700801
Makoto Onukid45a4a22015-11-02 17:17:38 -0800802 UserRestrictionsUtils.applyUserRestrictionsLR(
Makoto Onuki4f160732015-10-27 17:15:38 -0700803 mContext, userId, newRestrictions, prevRestrictions);
804
Makoto Onukid45a4a22015-11-02 17:17:38 -0800805 notifyUserRestrictionsListeners(userId, newRestrictions, prevRestrictions);
806
Makoto Onuki4f160732015-10-27 17:15:38 -0700807 mAppliedUserRestrictions.put(userId, new Bundle(newRestrictions));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700808 }
809
Makoto Onukid45a4a22015-11-02 17:17:38 -0800810 private void notifyUserRestrictionsListeners(final int userId,
811 Bundle newRestrictions, Bundle prevRestrictions) {
812
813 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
814 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
815
816 mHandler.post(new Runnable() {
817 @Override
818 public void run() {
819 final UserRestrictionsListener[] listeners;
820 synchronized (mUserRestrictionsListeners) {
821 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
822 mUserRestrictionsListeners.toArray(listeners);
823 }
824 for (int i = 0; i < listeners.length; i++) {
825 listeners[i].onUserRestrictionsChanged(userId,
826 newRestrictionsFinal, prevRestrictionsFinal);
827 }
828 }
829 });
830 }
831
Makoto Onuki068c54a2015-10-13 14:34:03 -0700832 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700833 private void updateEffectiveUserRestrictionsLR(int userId) {
834 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700835 }
836
837 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700838 private void updateEffectiveUserRestrictionsForAllUsersLR() {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700839 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700840 mCachedEffectiveUserRestrictions.clear();
841
Makoto Onuki068c54a2015-10-13 14:34:03 -0700842 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
843 // it on a handler.
844 final Runnable r = new Runnable() {
845 @Override
846 public void run() {
847 // Then get the list of running users.
848 final int[] runningUsers;
849 try {
850 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
851 } catch (RemoteException e) {
852 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
853 return;
854 }
855 // Then re-calculate the effective restrictions and apply, only for running users.
856 // It's okay if a new user has started after the getRunningUserIds() call,
857 // because we'll do the same thing (re-calculate the restrictions and apply)
858 // when we start a user.
859 // TODO: "Apply restrictions upon user start hasn't been implemented. Implement it.
860 synchronized (mRestrictionsLock) {
861 for (int i = 0; i < runningUsers.length; i++) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700862 updateUserRestrictionsInternalLR(null, runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700863 }
864 }
865 }
866 };
867 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700868 }
869
Amith Yamasani258848d2012-08-10 17:06:33 -0700870 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700871 * Check if we've hit the limit of how many users can be created.
872 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700873 private boolean isUserLimitReached() {
874 int count;
875 synchronized (mUsersLock) {
876 count = getAliveUsersExcludingGuestsCountLU();
877 }
878 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700879 }
880
881 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000882 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700883 checkManageUsersPermission("check if more managed profiles can be added.");
884 if (ActivityManager.isLowRamDeviceStatic()) {
885 return false;
886 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700887 if (!mContext.getPackageManager().hasSystemFeature(
888 PackageManager.FEATURE_MANAGED_USERS)) {
889 return false;
890 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100891 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000892 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
893 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
894 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100895 return false;
896 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700897 synchronized(mUsersLock) {
898 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100899 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700900 return false;
901 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000902 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
903 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -0700904 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000905 return usersCountAfterRemoving == 1
906 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700907 }
908 }
909
Fyodor Kupolov82402752015-10-28 14:54:51 -0700910 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700911 int aliveUserCount = 0;
912 final int totalUserCount = mUsers.size();
913 // Skip over users being removed
914 for (int i = 0; i < totalUserCount; i++) {
915 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700916 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700917 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700918 aliveUserCount++;
919 }
920 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700921 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700922 }
923
924 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700925 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700926 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700927 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700928 *
929 * @param message used as message if SecurityException is thrown
930 * @throws SecurityException if the caller is not system or root
931 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700932 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700933 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700934 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400935 && ActivityManager.checkComponentPermission(
936 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700937 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
938 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
939 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400940 }
941
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700942 private static void checkSystemOrRoot(String message) {
943 final int uid = Binder.getCallingUid();
944 if (uid != Process.SYSTEM_UID && uid != 0) {
945 throw new SecurityException("Only system may call: " + message);
946 }
947 }
948
Fyodor Kupolov82402752015-10-28 14:54:51 -0700949 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700950 try {
951 File dir = new File(mUsersDir, Integer.toString(info.id));
952 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100953 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700954 if (!dir.exists()) {
955 dir.mkdir();
956 FileUtils.setPermissions(
957 dir.getPath(),
958 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
959 -1, -1);
960 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700961 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100962 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
963 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700964 info.iconPath = file.getAbsolutePath();
965 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700966 try {
967 os.close();
968 } catch (IOException ioe) {
969 // What the ... !
970 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100971 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700972 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700973 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700974 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700975 }
976
Amith Yamasani0b285492011-04-14 17:35:23 -0700977 /**
978 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
979 * cache it elsewhere.
980 * @return the array of user ids.
981 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700982 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700983 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700984 return mUserIds;
985 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700986 }
987
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800988 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700989 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800990 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700991 return;
992 }
993 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700994 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700995 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700996 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700997 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100998 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700999 int type;
1000 while ((type = parser.next()) != XmlPullParser.START_TAG
1001 && type != XmlPullParser.END_DOCUMENT) {
1002 ;
1003 }
1004
1005 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001006 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001007 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001008 return;
1009 }
1010
Amith Yamasani2a003292012-08-14 18:25:45 -07001011 mNextSerialNumber = -1;
1012 if (parser.getName().equals(TAG_USERS)) {
1013 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1014 if (lastSerialNumber != null) {
1015 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1016 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001017 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1018 if (versionNumber != null) {
1019 mUserVersion = Integer.parseInt(versionNumber);
1020 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001021 }
1022
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001023 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301024 if (type == XmlPullParser.START_TAG) {
1025 final String name = parser.getName();
1026 if (name.equals(TAG_USER)) {
1027 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001028 UserInfo user = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001029
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301030 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001031 synchronized (mUsersLock) {
1032 mUsers.put(user.id, user);
1033 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1034 mNextSerialNumber = user.id + 1;
1035 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301036 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001037 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301038 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001039 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1040 && type != XmlPullParser.END_TAG) {
1041 if (type == XmlPullParser.START_TAG) {
1042 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001043 synchronized (mGuestRestrictions) {
1044 UserRestrictionsUtils
1045 .readRestrictions(parser, mGuestRestrictions);
1046 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001047 }
1048 break;
1049 }
1050 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001051 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001052 }
1053 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001054 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001055 upgradeIfNecessaryLP();
1056 } catch (IOException | XmlPullParserException e) {
1057 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001058 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001059 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001060 }
1061 }
1062
Amith Yamasani6f34b412012-10-22 18:19:27 -07001063 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001064 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001065 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001066 private void upgradeIfNecessaryLP() {
Amith Yamasani6f34b412012-10-22 18:19:27 -07001067 int userVersion = mUserVersion;
1068 if (userVersion < 1) {
1069 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001070 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001071 if ("Primary".equals(user.name)) {
1072 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001073 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001074 }
1075 userVersion = 1;
1076 }
1077
Amith Yamasanibc9625052012-11-15 14:39:18 -08001078 if (userVersion < 2) {
1079 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001080 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001081 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1082 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001083 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001084 }
1085 userVersion = 2;
1086 }
1087
Amith Yamasani350962c2013-08-06 11:18:53 -07001088
Amith Yamasani5e486f52013-08-07 11:06:44 -07001089 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001090 userVersion = 4;
1091 }
1092
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001093 if (userVersion < 5) {
1094 initDefaultGuestRestrictions();
1095 userVersion = 5;
1096 }
1097
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001098 if (userVersion < 6) {
1099 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001100 synchronized (mUsersLock) {
1101 for (int i = 0; i < mUsers.size(); i++) {
1102 UserInfo user = mUsers.valueAt(i);
1103 // In non-split mode, only user 0 can have restricted profiles
1104 if (!splitSystemUser && user.isRestricted()
1105 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1106 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001107 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001108 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001109 }
1110 }
1111 userVersion = 6;
1112 }
1113
Amith Yamasani6f34b412012-10-22 18:19:27 -07001114 if (userVersion < USER_VERSION) {
1115 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1116 + USER_VERSION);
1117 } else {
1118 mUserVersion = userVersion;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001119 writeUserListLP();
Amith Yamasani6f34b412012-10-22 18:19:27 -07001120 }
1121 }
1122
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001123 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001124 int flags = UserInfo.FLAG_INITIALIZED;
1125 // In split system user mode, the admin and primary flags are assigned to the first human
1126 // user.
1127 if (!UserManager.isSplitSystemUser()) {
1128 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1129 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001130 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001131 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001132 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001133 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001134 synchronized (mUsersLock) {
1135 mUsers.put(system.id, system);
1136 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001137 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001138 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001139
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001140 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001141 synchronized (mRestrictionsLock) {
1142 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1143 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001144
Fyodor Kupolov82402752015-10-28 14:54:51 -07001145 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001146 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001147
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001148 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001149 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001150 }
1151
Makoto Onuki9e935a32015-11-06 14:24:24 -08001152 private void scheduleWriteUser(UserInfo userInfo) {
1153 // No need to wrap it within a lock -- worst case, we'll just post the same message
1154 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001155 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1156 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1157 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1158 }
1159 }
1160
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001161 /*
1162 * Writes the user file in this format:
1163 *
1164 * <user flags="20039023" id="0">
1165 * <name>Primary</name>
1166 * </user>
1167 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001168 private void writeUserLP(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001169 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001170 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001171 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001172 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001173 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1174
1175 // XmlSerializer serializer = XmlUtils.serializerInstance();
1176 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001177 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001178 serializer.startDocument(null, true);
1179 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1180
1181 serializer.startTag(null, TAG_USER);
1182 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001183 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001184 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001185 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1186 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1187 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001188 if (userInfo.iconPath != null) {
1189 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1190 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001191 if (userInfo.partial) {
1192 serializer.attribute(null, ATTR_PARTIAL, "true");
1193 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001194 if (userInfo.guestToRemove) {
1195 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1196 }
Kenny Guy2a764942014-04-02 13:29:20 +01001197 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1198 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1199 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001200 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001201 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1202 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1203 Integer.toString(userInfo.restrictedProfileParentId));
1204 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001205 serializer.startTag(null, TAG_NAME);
1206 serializer.text(userInfo.name);
1207 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001208 Bundle restrictions;
1209 synchronized (mRestrictionsLock) {
1210 restrictions = mBaseUserRestrictions.get(userInfo.id);
1211 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001212 if (restrictions != null) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001213 UserRestrictionsUtils
1214 .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001215 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001216 serializer.endTag(null, TAG_USER);
1217
1218 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001219 userFile.finishWrite(fos);
1220 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001221 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001222 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001223 }
1224 }
1225
1226 /*
1227 * Writes the user list file in this format:
1228 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001229 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001230 * <user id="0"></user>
1231 * <user id="2"></user>
1232 * </users>
1233 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001234 private void writeUserListLP() {
Amith Yamasani742a6712011-05-04 14:49:28 -07001235 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001236 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001237 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001238 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001239 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1240
1241 // XmlSerializer serializer = XmlUtils.serializerInstance();
1242 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001243 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001244 serializer.startDocument(null, true);
1245 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1246
1247 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001248 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001249 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001250
Adam Lesinskieddeb492014-09-08 17:50:03 -07001251 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001252 synchronized (mGuestRestrictions) {
1253 UserRestrictionsUtils
1254 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1255 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301256 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001257 int[] userIdsToWrite;
1258 synchronized (mUsersLock) {
1259 userIdsToWrite = new int[mUsers.size()];
1260 for (int i = 0; i < userIdsToWrite.length; i++) {
1261 UserInfo user = mUsers.valueAt(i);
1262 userIdsToWrite[i] = user.id;
1263 }
1264 }
1265 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001266 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001267 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001268 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001269 }
1270
1271 serializer.endTag(null, TAG_USERS);
1272
1273 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001274 userListFile.finishWrite(fos);
1275 } catch (Exception e) {
1276 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001277 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001278 }
1279 }
1280
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001281 private UserInfo readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001282 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001283 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001284 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001285 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001286 long creationTime = 0L;
1287 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001288 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001289 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001290 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001291 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001292 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001293
1294 FileInputStream fis = null;
1295 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001296 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001297 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001298 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001299 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001300 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001301 int type;
1302 while ((type = parser.next()) != XmlPullParser.START_TAG
1303 && type != XmlPullParser.END_DOCUMENT) {
1304 ;
1305 }
1306
1307 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001308 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001309 return null;
1310 }
1311
1312 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001313 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1314 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001315 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001316 return null;
1317 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001318 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1319 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001320 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001321 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1322 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001323 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1324 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001325 restrictedProfileParentId = readIntAttribute(parser,
1326 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001327 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1328 if ("true".equals(valueString)) {
1329 partial = true;
1330 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001331 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1332 if ("true".equals(valueString)) {
1333 guestToRemove = true;
1334 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001335
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001336 int outerDepth = parser.getDepth();
1337 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1338 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1339 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1340 continue;
1341 }
1342 String tag = parser.getName();
1343 if (TAG_NAME.equals(tag)) {
1344 type = parser.next();
1345 if (type == XmlPullParser.TEXT) {
1346 name = parser.getText();
1347 }
1348 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001349 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001350 }
1351 }
1352 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001353
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001354 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001355 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001356 userInfo.creationTime = creationTime;
1357 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001358 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001359 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001360 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001361 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001362 synchronized (mRestrictionsLock) {
1363 mBaseUserRestrictions.append(id, restrictions);
1364 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001365 return userInfo;
1366
1367 } catch (IOException ioe) {
1368 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001369 } finally {
1370 if (fis != null) {
1371 try {
1372 fis.close();
1373 } catch (IOException e) {
1374 }
1375 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001376 }
1377 return null;
1378 }
1379
Amith Yamasani920ace02012-09-20 22:15:37 -07001380 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1381 String valueString = parser.getAttributeValue(null, attr);
1382 if (valueString == null) return defaultValue;
1383 try {
1384 return Integer.parseInt(valueString);
1385 } catch (NumberFormatException nfe) {
1386 return defaultValue;
1387 }
1388 }
1389
1390 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1391 String valueString = parser.getAttributeValue(null, attr);
1392 if (valueString == null) return defaultValue;
1393 try {
1394 return Long.parseLong(valueString);
1395 } catch (NumberFormatException nfe) {
1396 return defaultValue;
1397 }
1398 }
1399
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001400 private boolean isPackageInstalled(String pkg, int userId) {
1401 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1402 PackageManager.GET_UNINSTALLED_PACKAGES,
1403 userId);
1404 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1405 return false;
1406 }
1407 return true;
1408 }
1409
Amith Yamasanib82add22013-07-09 11:24:44 -07001410 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001411 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001412 * Does not do any permissions checking.
1413 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001414 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001415 synchronized (mPackagesLock) {
1416 File dir = Environment.getUserSystemDirectory(userId);
1417 String[] files = dir.list();
1418 if (files == null) return;
1419 for (String fileName : files) {
1420 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1421 File resFile = new File(dir, fileName);
1422 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001423 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001424 }
1425 }
1426 }
1427 }
1428 }
1429
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001430 /**
1431 * Removes the app restrictions file for a specific package and user id, if it exists.
1432 */
1433 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1434 synchronized (mPackagesLock) {
1435 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001436 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001437 if (resFile.exists()) {
1438 resFile.delete();
1439 }
1440 }
1441 }
1442
Kenny Guya52dc3e2014-02-11 15:33:14 +00001443 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001444 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001445 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001446 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001447 }
1448
Amith Yamasani258848d2012-08-10 17:06:33 -07001449 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001450 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001451 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001452 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001453 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001454
Jessica Hummelbe81c802014-04-22 15:49:22 +01001455 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001456 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001457 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1458 return null;
1459 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001460 if (ActivityManager.isLowRamDeviceStatic()) {
1461 return null;
1462 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001463 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001464 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001465 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001466 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001467 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001468 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001469 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001470 synchronized (mPackagesLock) {
1471 UserInfo parent = null;
1472 if (parentId != UserHandle.USER_NULL) {
1473 synchronized (mUsersLock) {
1474 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001475 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001476 if (parent == null) return null;
1477 }
1478 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1479 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1480 return null;
1481 }
1482 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1483 // If we're not adding a guest user or a managed profile and the limit has
1484 // been reached, cannot add a user.
1485 return null;
1486 }
1487 // If we're adding a guest and there already exists one, bail.
1488 if (isGuest && findCurrentGuestUser() != null) {
1489 return null;
1490 }
1491 // In legacy mode, restricted profile's parent can only be the owner user
1492 if (isRestricted && !UserManager.isSplitSystemUser()
1493 && (parentId != UserHandle.USER_SYSTEM)) {
1494 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1495 return null;
1496 }
1497 if (isRestricted && UserManager.isSplitSystemUser()) {
1498 if (parent == null) {
1499 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1500 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001501 return null;
1502 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001503 if (!parent.canHaveProfile()) {
1504 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1505 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001506 return null;
1507 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001508 }
1509 // In split system user mode, we assign the first human user the primary flag.
1510 // And if there is no device owner, we also assign the admin flag to primary user.
1511 if (UserManager.isSplitSystemUser()
1512 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1513 flags |= UserInfo.FLAG_PRIMARY;
1514 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1515 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1516 if (devicePolicyManager == null
1517 || devicePolicyManager.getDeviceOwner() == null) {
1518 flags |= UserInfo.FLAG_ADMIN;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001519 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001520 }
1521 userId = getNextAvailableId();
1522 userInfo = new UserInfo(userId, name, null, flags);
1523 userInfo.serialNumber = mNextSerialNumber++;
1524 long now = System.currentTimeMillis();
1525 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1526 userInfo.partial = true;
1527 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1528 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001529 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001530 }
1531 writeUserListLP();
1532 if (parent != null) {
1533 if (isManagedProfile) {
1534 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1535 parent.profileGroupId = parent.id;
1536 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001537 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001538 userInfo.profileGroupId = parent.profileGroupId;
1539 } else if (isRestricted) {
1540 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1541 parent.restrictedProfileParentId = parent.id;
1542 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001543 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001544 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001545 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001546 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001547 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001548 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1549 storage.createUserKey(userId, userInfo.serialNumber);
1550 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1551 final String volumeUuid = vol.getFsUuid();
1552 try {
1553 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1554 storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
1555 enforceSerialNumber(userDir, userInfo.serialNumber);
1556 } catch (IOException e) {
1557 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1558 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001559 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001560 mPm.createNewUser(userId);
1561 userInfo.partial = false;
1562 synchronized (mPackagesLock) {
1563 writeUserLP(userInfo);
1564 }
1565 updateUserIds();
1566 Bundle restrictions = new Bundle();
1567 synchronized (mRestrictionsLock) {
1568 mBaseUserRestrictions.append(userId, restrictions);
1569 }
1570 mPm.newUserCreated(userId);
1571 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1572 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1573 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1574 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001575 } finally {
1576 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001577 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001578 return userInfo;
1579 }
1580
Amith Yamasani0b285492011-04-14 17:35:23 -07001581 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001582 * @hide
1583 */
1584 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1585 checkManageUsersPermission("setupRestrictedProfile");
1586 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1587 if (user == null) {
1588 return null;
1589 }
1590 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1591 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1592 // the putIntForUser() will fail.
1593 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1594 android.provider.Settings.Secure.LOCATION_MODE,
1595 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1596 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1597 return user;
1598 }
1599
1600 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001601 * Find the current guest user. If the Guest user is partial,
1602 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001603 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001604 private UserInfo findCurrentGuestUser() {
1605 synchronized (mUsersLock) {
1606 final int size = mUsers.size();
1607 for (int i = 0; i < size; i++) {
1608 final UserInfo user = mUsers.valueAt(i);
1609 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1610 return user;
1611 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001612 }
1613 }
1614 return null;
1615 }
1616
1617 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001618 * Mark this guest user for deletion to allow us to create another guest
1619 * and switch to that user before actually removing this guest.
1620 * @param userHandle the userid of the current guest
1621 * @return whether the user could be marked for deletion
1622 */
1623 public boolean markGuestForDeletion(int userHandle) {
1624 checkManageUsersPermission("Only the system can remove users");
1625 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1626 UserManager.DISALLOW_REMOVE_USER, false)) {
1627 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1628 return false;
1629 }
1630
1631 long ident = Binder.clearCallingIdentity();
1632 try {
1633 final UserInfo user;
1634 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001635 synchronized (mUsersLock) {
1636 user = mUsers.get(userHandle);
1637 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1638 return false;
1639 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001640 }
1641 if (!user.isGuest()) {
1642 return false;
1643 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001644 // We set this to a guest user that is to be removed. This is a temporary state
1645 // where we are allowed to add new Guest users, even if this one is still not
1646 // removed. This user will still show up in getUserInfo() calls.
1647 // If we don't get around to removing this Guest user, it will be purged on next
1648 // startup.
1649 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001650 // Mark it as disabled, so that it isn't returned any more when
1651 // profiles are queried.
1652 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001653 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001654 }
1655 } finally {
1656 Binder.restoreCallingIdentity(ident);
1657 }
1658 return true;
1659 }
1660
1661 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001662 * Removes a user and all data directories created for that user. This method should be called
1663 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001664 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001665 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001666 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001667 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001668 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1669 UserManager.DISALLOW_REMOVE_USER, false)) {
1670 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1671 return false;
1672 }
1673
Kenny Guyee58b4f2014-05-23 15:19:53 +01001674 long ident = Binder.clearCallingIdentity();
1675 try {
1676 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001677 int currentUser = ActivityManager.getCurrentUser();
1678 if (currentUser == userHandle) {
1679 Log.w(LOG_TAG, "Current user cannot be removed");
1680 return false;
1681 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001682 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001683 synchronized (mUsersLock) {
1684 user = mUsers.get(userHandle);
1685 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1686 return false;
1687 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001688
Fyodor Kupolov82402752015-10-28 14:54:51 -07001689 // We remember deleted user IDs to prevent them from being
1690 // reused during the current boot; they can still be reused
1691 // after a reboot.
1692 mRemovingUserIds.put(userHandle, true);
1693 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001694
Kenny Guyee58b4f2014-05-23 15:19:53 +01001695 try {
1696 mAppOpsService.removeUser(userHandle);
1697 } catch (RemoteException e) {
1698 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1699 }
1700 // Set this to a partially created user, so that the user will be purged
1701 // on next startup, in case the runtime stops now before stopping and
1702 // removing the user completely.
1703 user.partial = true;
1704 // Mark it as disabled, so that it isn't returned any more when
1705 // profiles are queried.
1706 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001707 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001708 }
1709
1710 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1711 && user.isManagedProfile()) {
1712 // Send broadcast to notify system that the user removed was a
1713 // managed user.
1714 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1715 }
1716
1717 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1718 int res;
1719 try {
1720 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1721 new IStopUserCallback.Stub() {
1722 @Override
1723 public void userStopped(int userId) {
1724 finishRemoveUser(userId);
1725 }
1726 @Override
1727 public void userStopAborted(int userId) {
1728 }
1729 });
1730 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001731 return false;
1732 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001733 return res == ActivityManager.USER_OP_SUCCESS;
1734 } finally {
1735 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001736 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001737 }
1738
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001739 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001740 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001741 // Let other services shutdown any activity and clean up their state before completely
1742 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001743 long ident = Binder.clearCallingIdentity();
1744 try {
1745 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1746 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001747 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1748 android.Manifest.permission.MANAGE_USERS,
1749
1750 new BroadcastReceiver() {
1751 @Override
1752 public void onReceive(Context context, Intent intent) {
1753 if (DBG) {
1754 Slog.i(LOG_TAG,
1755 "USER_REMOVED broadcast sent, cleaning up user data "
1756 + userHandle);
1757 }
1758 new Thread() {
1759 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001760 // Clean up any ActivityManager state
1761 LocalServices.getService(ActivityManagerInternal.class)
1762 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001763 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001764 }
1765 }.start();
1766 }
1767 },
1768
1769 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001770 } finally {
1771 Binder.restoreCallingIdentity(ident);
1772 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001773 }
1774
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001775 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001776 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001777 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001778 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001779
1780 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001781 synchronized (mUsersLock) {
1782 mUsers.remove(userHandle);
1783 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001784 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001785 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001786 userFile.delete();
1787 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001788 synchronized (mPackagesLock) {
1789 writeUserListLP();
1790 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001791 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001792 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1793 }
1794
Amith Yamasani61f57372012-08-31 12:12:28 -07001795 private void removeDirectoryRecursive(File parent) {
1796 if (parent.isDirectory()) {
1797 String[] files = parent.list();
1798 for (String filename : files) {
1799 File child = new File(parent, filename);
1800 removeDirectoryRecursive(child);
1801 }
1802 }
1803 parent.delete();
1804 }
1805
Kenny Guyf8d3a232014-05-15 16:09:52 +01001806 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001807 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001808 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1809 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001810 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1811 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001812 }
1813
Amith Yamasani2a003292012-08-14 18:25:45 -07001814 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001815 public Bundle getApplicationRestrictions(String packageName) {
1816 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1817 }
1818
1819 @Override
1820 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001821 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001822 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001823 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001824 }
1825 synchronized (mPackagesLock) {
1826 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001827 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001828 }
1829 }
1830
1831 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001832 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001833 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001834 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001835 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001836 if (restrictions == null || restrictions.isEmpty()) {
1837 cleanAppRestrictionsForPackage(packageName, userId);
1838 } else {
1839 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001840 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001841 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001842 }
Robin Lee66e5d962014-04-09 16:44:21 +01001843
Kenny Guyd21b2182014-07-17 16:38:55 +01001844 if (isPackageInstalled(packageName, userId)) {
1845 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1846 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1847 changeIntent.setPackage(packageName);
1848 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1849 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1850 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001851 }
1852
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001853 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001854 mHandler.post(new Runnable() {
1855 @Override
1856 public void run() {
1857 List<ApplicationInfo> apps =
1858 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1859 userHandle).getList();
1860 final long ident = Binder.clearCallingIdentity();
1861 try {
1862 for (ApplicationInfo appInfo : apps) {
1863 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001864 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1865 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001866 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001867 userHandle);
1868 }
1869 }
1870 } finally {
1871 Binder.restoreCallingIdentity(ident);
1872 }
1873 }
1874 });
1875 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001876 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001877 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001878 try {
1879 return mContext.getPackageManager().getApplicationInfo(packageName,
1880 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1881 } catch (NameNotFoundException nnfe) {
1882 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001883 } finally {
1884 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001885 }
1886 }
1887
Fyodor Kupolov82402752015-10-28 14:54:51 -07001888 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001889 AtomicFile restrictionsFile =
1890 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1891 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001892 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001893 }
1894
1895 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001896 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001897 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001898 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001899 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001900 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001901 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001902
1903 FileInputStream fis = null;
1904 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001905 fis = restrictionsFile.openRead();
1906 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001907 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001908 XmlUtils.nextElement(parser);
1909 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001910 Slog.e(LOG_TAG, "Unable to read restrictions file "
1911 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001912 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001913 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001914 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1915 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001916 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001917 } catch (IOException|XmlPullParserException e) {
1918 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001919 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001920 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001921 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001922 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001923 }
1924
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001925 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1926 XmlPullParser parser) throws XmlPullParserException, IOException {
1927 int type = parser.getEventType();
1928 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1929 String key = parser.getAttributeValue(null, ATTR_KEY);
1930 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1931 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1932 if (multiple != null) {
1933 values.clear();
1934 int count = Integer.parseInt(multiple);
1935 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1936 if (type == XmlPullParser.START_TAG
1937 && parser.getName().equals(TAG_VALUE)) {
1938 values.add(parser.nextText().trim());
1939 count--;
1940 }
1941 }
1942 String [] valueStrings = new String[values.size()];
1943 values.toArray(valueStrings);
1944 restrictions.putStringArray(key, valueStrings);
1945 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1946 restrictions.putBundle(key, readBundleEntry(parser, values));
1947 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1948 final int outerDepth = parser.getDepth();
1949 ArrayList<Bundle> bundleList = new ArrayList<>();
1950 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1951 Bundle childBundle = readBundleEntry(parser, values);
1952 bundleList.add(childBundle);
1953 }
1954 restrictions.putParcelableArray(key,
1955 bundleList.toArray(new Bundle[bundleList.size()]));
1956 } else {
1957 String value = parser.nextText().trim();
1958 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1959 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1960 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1961 restrictions.putInt(key, Integer.parseInt(value));
1962 } else {
1963 restrictions.putString(key, value);
1964 }
1965 }
1966 }
1967 }
1968
1969 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1970 throws IOException, XmlPullParserException {
1971 Bundle childBundle = new Bundle();
1972 final int outerDepth = parser.getDepth();
1973 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1974 readEntry(childBundle, values, parser);
1975 }
1976 return childBundle;
1977 }
1978
Fyodor Kupolov82402752015-10-28 14:54:51 -07001979 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001980 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001981 AtomicFile restrictionsFile = new AtomicFile(
1982 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001983 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001984 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001985 }
1986
1987 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001988 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001989 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001990 try {
1991 fos = restrictionsFile.startWrite();
1992 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1993
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001994 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001995 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001996 serializer.startDocument(null, true);
1997 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1998
1999 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002000 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002001 serializer.endTag(null, TAG_RESTRICTIONS);
2002
2003 serializer.endDocument();
2004 restrictionsFile.finishWrite(fos);
2005 } catch (Exception e) {
2006 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002007 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2008 }
2009 }
2010
2011 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2012 throws IOException {
2013 for (String key : restrictions.keySet()) {
2014 Object value = restrictions.get(key);
2015 serializer.startTag(null, TAG_ENTRY);
2016 serializer.attribute(null, ATTR_KEY, key);
2017
2018 if (value instanceof Boolean) {
2019 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2020 serializer.text(value.toString());
2021 } else if (value instanceof Integer) {
2022 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2023 serializer.text(value.toString());
2024 } else if (value == null || value instanceof String) {
2025 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2026 serializer.text(value != null ? (String) value : "");
2027 } else if (value instanceof Bundle) {
2028 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2029 writeBundle((Bundle) value, serializer);
2030 } else if (value instanceof Parcelable[]) {
2031 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2032 Parcelable[] array = (Parcelable[]) value;
2033 for (Parcelable parcelable : array) {
2034 if (!(parcelable instanceof Bundle)) {
2035 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2036 }
2037 serializer.startTag(null, TAG_ENTRY);
2038 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2039 writeBundle((Bundle) parcelable, serializer);
2040 serializer.endTag(null, TAG_ENTRY);
2041 }
2042 } else {
2043 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2044 String[] values = (String[]) value;
2045 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2046 for (String choice : values) {
2047 serializer.startTag(null, TAG_VALUE);
2048 serializer.text(choice != null ? choice : "");
2049 serializer.endTag(null, TAG_VALUE);
2050 }
2051 }
2052 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002053 }
2054 }
2055
2056 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002057 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002058 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002059 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002060 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002061 }
2062 }
2063
2064 @Override
2065 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002066 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002067 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002068 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002069 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002070 }
2071 // Not found
2072 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002073 }
2074 }
2075
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002076 @Override
2077 public long getUserCreationTime(int userHandle) {
2078 int callingUserId = UserHandle.getCallingUserId();
2079 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002080 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002081 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002082 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002083 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002084 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002085 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002086 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002087 }
2088 }
2089 }
2090 if (userInfo == null) {
2091 throw new SecurityException("userHandle can only be the calling user or a managed "
2092 + "profile associated with this user");
2093 }
2094 return userInfo.creationTime;
2095 }
2096
Amith Yamasani0b285492011-04-14 17:35:23 -07002097 /**
2098 * Caches the list of user ids in an array, adjusting the array size when necessary.
2099 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002100 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002101 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002102 synchronized (mUsersLock) {
2103 final int userSize = mUsers.size();
2104 for (int i = 0; i < userSize; i++) {
2105 if (!mUsers.valueAt(i).partial) {
2106 num++;
2107 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002108 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002109 final int[] newUsers = new int[num];
2110 int n = 0;
2111 for (int i = 0; i < userSize; i++) {
2112 if (!mUsers.valueAt(i).partial) {
2113 newUsers[n++] = mUsers.keyAt(i);
2114 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002115 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002116 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002117 }
2118 }
2119
2120 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002121 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002122 * @param userId the user that was just foregrounded
2123 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002124 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002125 UserInfo user = getUserInfoNoChecks(userId);
2126 if (user == null || user.partial) {
2127 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2128 return;
2129 }
2130 long now = System.currentTimeMillis();
2131 if (now > EPOCH_PLUS_30_YEARS) {
2132 user.lastLoggedInTime = now;
2133 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002134 }
2135 }
2136
2137 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002138 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002139 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2140 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002141 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002142 private int getNextAvailableId() {
2143 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002144 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002145 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002146 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002147 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002148 }
2149 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002150 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002151 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002152 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002153 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002154
Amith Yamasanifc95e702013-09-26 13:20:17 -07002155 private String packageToRestrictionsFileName(String packageName) {
2156 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2157 }
2158
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002159 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002160 * Enforce that serial number stored in user directory inode matches the
2161 * given expected value. Gracefully sets the serial number if currently
2162 * undefined.
2163 *
2164 * @throws IOException when problem extracting serial number, or serial
2165 * number is mismatched.
2166 */
2167 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2168 final int foundSerial = getSerialNumber(file);
2169 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2170
2171 if (foundSerial == -1) {
2172 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2173 try {
2174 setSerialNumber(file, serialNumber);
2175 } catch (IOException e) {
2176 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2177 }
2178
2179 } else if (foundSerial != serialNumber) {
2180 throw new IOException("Found serial number " + foundSerial
2181 + " doesn't match expected " + serialNumber);
2182 }
2183 }
2184
2185 /**
2186 * Set serial number stored in user directory inode.
2187 *
2188 * @throws IOException if serial number was already set
2189 */
2190 private static void setSerialNumber(File file, int serialNumber)
2191 throws IOException {
2192 try {
2193 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2194 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2195 } catch (ErrnoException e) {
2196 throw e.rethrowAsIOException();
2197 }
2198 }
2199
2200 /**
2201 * Return serial number stored in user directory inode.
2202 *
2203 * @return parsed serial number, or -1 if not set
2204 */
2205 private static int getSerialNumber(File file) throws IOException {
2206 try {
2207 final byte[] buf = new byte[256];
2208 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2209 final String serial = new String(buf, 0, len);
2210 try {
2211 return Integer.parseInt(serial);
2212 } catch (NumberFormatException e) {
2213 throw new IOException("Bad serial number: " + serial);
2214 }
2215 } catch (ErrnoException e) {
2216 if (e.errno == OsConstants.ENODATA) {
2217 return -1;
2218 } else {
2219 throw e.rethrowAsIOException();
2220 }
2221 }
2222 }
2223
Amith Yamasani920ace02012-09-20 22:15:37 -07002224 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002225 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2226 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2227 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2228 }
2229
2230 int onShellCommand(Shell shell, String cmd) {
2231 if (cmd == null) {
2232 return shell.handleDefaultCommands(cmd);
2233 }
2234
2235 final PrintWriter pw = shell.getOutPrintWriter();
2236 try {
2237 switch(cmd) {
2238 case "list":
2239 return runList(pw);
2240 }
2241 } catch (RemoteException e) {
2242 pw.println("Remote exception: " + e);
2243 }
2244 return -1;
2245 }
2246
2247 private int runList(PrintWriter pw) throws RemoteException {
2248 final IActivityManager am = ActivityManagerNative.getDefault();
2249 final List<UserInfo> users = getUsers(false);
2250 if (users == null) {
2251 pw.println("Error: couldn't get users");
2252 return 1;
2253 } else {
2254 pw.println("Users:");
2255 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002256 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002257 pw.println("\t" + users.get(i).toString() + running);
2258 }
2259 return 0;
2260 }
2261 }
2262
2263 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002264 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2265 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2266 != PackageManager.PERMISSION_GRANTED) {
2267 pw.println("Permission Denial: can't dump UserManager from from pid="
2268 + Binder.getCallingPid()
2269 + ", uid=" + Binder.getCallingUid()
2270 + " without permission "
2271 + android.Manifest.permission.DUMP);
2272 return;
2273 }
2274
2275 long now = System.currentTimeMillis();
2276 StringBuilder sb = new StringBuilder();
2277 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002278 synchronized (mUsersLock) {
2279 pw.println("Users:");
2280 for (int i = 0; i < mUsers.size(); i++) {
2281 UserInfo user = mUsers.valueAt(i);
2282 if (user == null) {
2283 continue;
2284 }
2285 pw.print(" "); pw.print(user);
2286 pw.print(" serialNo="); pw.print(user.serialNumber);
2287 if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2288 pw.print(" <removing> ");
2289 }
2290 if (user.partial) {
2291 pw.print(" <partial>");
2292 }
2293 pw.println();
2294 pw.print(" Created: ");
2295 if (user.creationTime == 0) {
2296 pw.println("<unknown>");
2297 } else {
2298 sb.setLength(0);
2299 TimeUtils.formatDuration(now - user.creationTime, sb);
2300 sb.append(" ago");
2301 pw.println(sb);
2302 }
2303 pw.print(" Last logged in: ");
2304 if (user.lastLoggedInTime == 0) {
2305 pw.println("<unknown>");
2306 } else {
2307 sb.setLength(0);
2308 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2309 sb.append(" ago");
2310 pw.println(sb);
2311 }
2312 pw.println(" Restrictions:");
2313 synchronized (mRestrictionsLock) {
2314 UserRestrictionsUtils.dumpRestrictions(
2315 pw, " ", mBaseUserRestrictions.get(user.id));
2316 pw.println(" Effective restrictions:");
2317 UserRestrictionsUtils.dumpRestrictions(
2318 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2319 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002320 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002321 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002322 pw.println();
2323 pw.println("Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002324 synchronized (mGuestRestrictions) {
2325 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
2326 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002327 }
2328 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002329
2330 final class MainHandler extends Handler {
2331
2332 @Override
2333 public void handleMessage(Message msg) {
2334 switch (msg.what) {
2335 case WRITE_USER_MSG:
2336 removeMessages(WRITE_USER_MSG, msg.obj);
2337 synchronized (mPackagesLock) {
2338 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002339 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002340 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002341 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002342 }
2343 }
2344 }
2345 }
2346 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002347
2348 /**
2349 * @param userId
2350 * @return whether the user has been initialized yet
2351 */
2352 boolean isInitialized(int userId) {
2353 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2354 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002355
2356 private class LocalService extends UserManagerInternal {
2357
2358 @Override
2359 public Object getUserRestrictionsLock() {
2360 return mRestrictionsLock;
2361 }
2362
2363 @Override
2364 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002365 public void updateEffectiveUserRestrictionsLR(int userId) {
2366 UserManagerService.this.updateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002367 }
2368
2369 @Override
2370 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002371 public void updateEffectiveUserRestrictionsForAllUsersLR() {
2372 UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersLR();
Makoto Onuki068c54a2015-10-13 14:34:03 -07002373 }
2374
2375 @Override
2376 public Bundle getBaseUserRestrictions(int userId) {
2377 synchronized (mRestrictionsLock) {
2378 return mBaseUserRestrictions.get(userId);
2379 }
2380 }
2381
2382 @Override
2383 public void setBaseUserRestrictionsByDpmsForMigration(
2384 int userId, Bundle baseRestrictions) {
2385 synchronized (mRestrictionsLock) {
2386 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002387 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002388 }
2389
Fyodor Kupolov82402752015-10-28 14:54:51 -07002390 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002391 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002392 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002393 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002394 } else {
2395 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2396 }
2397 }
2398 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002399
2400 @Override
2401 public boolean getUserRestriction(int userId, String key) {
2402 return getUserRestrictions(userId).getBoolean(key);
2403 }
2404
2405 @Override
2406 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2407 synchronized (mUserRestrictionsListeners) {
2408 mUserRestrictionsListeners.add(listener);
2409 }
2410 }
2411
2412 @Override
2413 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2414 synchronized (mUserRestrictionsListeners) {
2415 mUserRestrictionsListeners.remove(listener);
2416 }
2417 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002418 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002419
2420 private class Shell extends ShellCommand {
2421 @Override
2422 public int onCommand(String cmd) {
2423 return onShellCommand(this, cmd);
2424 }
2425
2426 @Override
2427 public void onHelp() {
2428 final PrintWriter pw = getOutPrintWriter();
2429 pw.println("User manager (user) commands:");
2430 pw.println(" help");
2431 pw.println(" Print this help text.");
2432 pw.println("");
2433 pw.println(" list");
2434 pw.println(" Prints all users on the system.");
2435 }
2436 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002437}