blob: 571ea82a17958139b8a92b254e1f1180c8337c3f [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 Chenb3b92582015-12-07 11:22:13 -080019import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070021import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070022import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070023import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070024import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070026import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070031import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070032import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080033import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070035import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080038import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070039import android.os.Environment;
40import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080041import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080043import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010044import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070045import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070047import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070048import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040049import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070050import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070051import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070052import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070053import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080054import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010055import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070056import android.os.storage.VolumeInfo;
57import android.system.ErrnoException;
58import android.system.Os;
59import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070060import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070061import android.util.Log;
Xiaohui Chenb3b92582015-12-07 11:22:13 -080062import android.util.Pair;
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;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000075import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070076import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080077
78import org.xmlpull.v1.XmlPullParser;
79import org.xmlpull.v1.XmlPullParserException;
80import org.xmlpull.v1.XmlSerializer;
81
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import java.io.BufferedOutputStream;
83import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070084import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070086import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087import java.io.FileOutputStream;
88import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070089import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010090import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070091import java.util.ArrayList;
92import java.util.List;
93
Fyodor Kupolov262f9952015-03-23 18:55:11 -070094import libcore.io.IoUtils;
Xiaohui Chenb3b92582015-12-07 11:22:13 -080095import libcore.util.Objects;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070096
Makoto Onuki068c54a2015-10-13 14:34:03 -070097/**
98 * Service for {@link UserManager}.
99 *
100 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700101 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800102 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700103 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
104 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
105 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700106 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700107public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700108 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800109 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
110 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700111
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800113 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700115 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700117 private static final String ATTR_CREATION_TIME = "created";
118 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700119 private static final String ATTR_SERIAL_NO = "serialNumber";
120 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700121 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700122 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700123 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100124 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700125 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530126 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700127 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800129 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800130 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800131 private static final String TAG_ENTRY = "entry";
132 private static final String TAG_VALUE = "value";
133 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700134 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800135 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700137 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
138 private static final String ATTR_TYPE_STRING = "s";
139 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700140 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700141 private static final String ATTR_TYPE_BUNDLE = "B";
142 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700143
Amith Yamasani0b285492011-04-14 17:35:23 -0700144 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700146 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100147 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700148
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800149 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700150 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800151
Amith Yamasani634cf312012-10-04 17:34:21 -0700152 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700153 // We need to keep process uid within Integer.MAX_VALUE.
154 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700155
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700156 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700157
Amith Yamasani920ace02012-09-20 22:15:37 -0700158 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
159
Nicolas Prevotb8186812015-08-06 15:00:03 +0100160 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700161 // without first making sure that the rest of the framework is prepared for it.
162 private static final int MAX_MANAGED_PROFILES = 1;
163
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800164 static final int WRITE_USER_MSG = 1;
165 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530166
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700167 private static final String XATTR_SERIAL = "user.serial";
168
Dianne Hackborn4428e172012-08-24 17:43:05 -0700169 private final Context mContext;
170 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700171 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700172 // Short-term lock for internal state, when interaction/sync with PM is not required
173 private final Object mUsersLock = new Object();
174 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700175
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800176 private final Handler mHandler;
177
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700178 private final File mUsersDir;
179 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700180
Fyodor Kupolov82402752015-10-28 14:54:51 -0700181 @GuardedBy("mUsersLock")
182 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700183
184 /**
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800185 * This collection contains each user's account name if the user chose to set one up
186 * during the initial user creation process. Keeping this information separate from mUsers
187 * to avoid accidentally leak it.
188 */
189 @GuardedBy("mUsersLock")
190 private final SparseArray<String> mUserAccounts = new SparseArray<>();
191
192 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700193 * User restrictions set via UserManager. This doesn't include restrictions set by
194 * device owner / profile owners.
195 *
196 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
197 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
198 * maybe shared between {@link #mBaseUserRestrictions} and
199 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
200 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700201 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700202 */
203 @GuardedBy("mRestrictionsLock")
204 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
205
206 /**
207 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
208 * with device / profile owner restrictions. We'll initialize it lazily; use
209 * {@link #getEffectiveUserRestrictions} to access it.
210 *
211 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
212 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
213 * maybe shared between {@link #mBaseUserRestrictions} and
214 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
215 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700216 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700217 */
218 @GuardedBy("mRestrictionsLock")
219 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
220
Makoto Onuki4f160732015-10-27 17:15:38 -0700221 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800222 * User restrictions that have already been applied in
223 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
224 * that have changed since the last
225 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700226 */
227 @GuardedBy("mRestrictionsLock")
228 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
229
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800230 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800231 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
232 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800233 */
234 @GuardedBy("mRestrictionsLock")
235 private Bundle mDevicePolicyGlobalUserRestrictions;
236
237 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800238 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
239 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800240 */
241 @GuardedBy("mRestrictionsLock")
242 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
243
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800244 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530245 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800246
247 /**
248 * Set of user IDs being actively removed. Removed IDs linger in this set
249 * for several seconds to work around a VFS caching issue.
250 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700251 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800252 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700253
Fyodor Kupolov82402752015-10-28 14:54:51 -0700254 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700255 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800256 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700257 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700258 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700259
Jason Monk62062992014-05-06 09:55:28 -0400260 private IAppOpsService mAppOpsService;
261
Makoto Onuki068c54a2015-10-13 14:34:03 -0700262 private final LocalService mLocalService;
263
Makoto Onukie7927da2015-11-25 10:05:17 -0800264 @GuardedBy("mUsersLock")
265 private boolean mIsDeviceManaged;
266
267 @GuardedBy("mUsersLock")
268 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
269
Makoto Onukid45a4a22015-11-02 17:17:38 -0800270 @GuardedBy("mUserRestrictionsListeners")
271 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
272 new ArrayList<>();
273
Amith Yamasani258848d2012-08-10 17:06:33 -0700274 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700275
Dianne Hackborn4428e172012-08-24 17:43:05 -0700276 public static UserManagerService getInstance() {
277 synchronized (UserManagerService.class) {
278 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700279 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700280 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700281
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800282 @VisibleForTesting
283 UserManagerService(File dataDir) {
284 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700285 }
286
Dianne Hackborn4428e172012-08-24 17:43:05 -0700287 /**
288 * Called by package manager to create the service. This is closely
289 * associated with the package manager, and the given lock is the
290 * package manager's own lock.
291 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800292 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
293 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700294 }
295
Dianne Hackborn4428e172012-08-24 17:43:05 -0700296 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800297 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700298 mContext = context;
299 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700300 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800301 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800302 synchronized (mPackagesLock) {
303 mUsersDir = new File(dataDir, USER_INFO_DIR);
304 mUsersDir.mkdirs();
305 // Make zeroth user directory, for services to migrate their files to that location
306 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
307 userZeroDir.mkdirs();
308 FileUtils.setPermissions(mUsersDir.toString(),
309 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
310 -1, -1);
311 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
312 initDefaultGuestRestrictions();
313 readUserListLP();
314 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700315 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700316 mLocalService = new LocalService();
317 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700318 }
319
320 void systemReady() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800321 // Prune out any partially created/partially removed users.
322 ArrayList<UserInfo> partials = new ArrayList<>();
323 synchronized (mUsersLock) {
324 final int userSize = mUsers.size();
325 for (int i = 0; i < userSize; i++) {
326 UserInfo ui = mUsers.valueAt(i);
327 if ((ui.partial || ui.guestToRemove) && i != 0) {
328 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700329 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700330 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700331 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800332 final int partialsSize = partials.size();
333 for (int i = 0; i < partialsSize; i++) {
334 UserInfo ui = partials.get(i);
335 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
336 + " (name=" + ui.name + ")");
337 removeUserState(ui.id);
338 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800339
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700340 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800341
Jason Monk62062992014-05-06 09:55:28 -0400342 mAppOpsService = IAppOpsService.Stub.asInterface(
343 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800344
345 synchronized (mRestrictionsLock) {
346 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400347 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700348 }
349
350 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800351 public String getUserAccount(int userId) {
352 checkManageUserAndAcrossUsersFullPermission("get user account");
353 synchronized (mUsersLock) {
354 return mUserAccounts.get(userId);
355 }
356 }
357
358 @Override
359 public void setUserAccount(int userId, String accountName) {
360 checkManageUserAndAcrossUsersFullPermission("set user account");
361 UserInfo userToUpdate = null;
362 synchronized (mPackagesLock) {
363 synchronized (mUsersLock) {
364 String currentAccount = mUserAccounts.get(userId);
365 if (!Objects.equal(currentAccount, accountName)) {
366 mUserAccounts.put(userId, accountName);
367 userToUpdate = mUsers.get(userId);
368 }
369 }
370
371 if (userToUpdate != null) {
372 writeUserLP(userToUpdate);
373 }
374 }
375 }
376
377 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700378 public UserInfo getPrimaryUser() {
379 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700380 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700381 final int userSize = mUsers.size();
382 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700383 UserInfo ui = mUsers.valueAt(i);
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800384 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700385 return ui;
386 }
387 }
388 }
389 return null;
390 }
391
392 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700393 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700394 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700395 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700396 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700397 final int userSize = mUsers.size();
398 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700399 UserInfo ui = mUsers.valueAt(i);
400 if (ui.partial) {
401 continue;
402 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800403 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700404 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700405 }
Amith Yamasani13593602012-03-22 16:16:17 -0700406 }
407 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700408 }
Amith Yamasani13593602012-03-22 16:16:17 -0700409 }
410
Amith Yamasani258848d2012-08-10 17:06:33 -0700411 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100412 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800413 if (userId != UserHandle.getCallingUserId()) {
414 checkManageUsersPermission("getting profiles related to user " + userId);
415 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700416 final long ident = Binder.clearCallingIdentity();
417 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700418 synchronized (mUsersLock) {
419 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100420 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700421 } finally {
422 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000423 }
424 }
425
Amith Yamasanibe465322014-04-24 13:45:17 -0700426 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700427 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
428 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700429 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700430 if (user == null) {
431 // Probably a dying user
432 return users;
433 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700434 final int userSize = mUsers.size();
435 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700436 UserInfo profile = mUsers.valueAt(i);
437 if (!isProfileOf(user, profile)) {
438 continue;
439 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100440 if (enabledOnly && !profile.isEnabled()) {
441 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700442 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700443 if (mRemovingUserIds.get(profile.id)) {
444 continue;
445 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700446 users.add(profile);
447 }
448 return users;
449 }
450
Jessica Hummelbe81c802014-04-22 15:49:22 +0100451 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700452 public int getCredentialOwnerProfile(int userHandle) {
453 checkManageUsersPermission("get the credential owner");
Clara Bayarri10ad84a2015-12-01 17:38:05 +0000454 if (!LockPatternUtils.isSeparateWorkChallengeEnabled()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700455 synchronized (mUsersLock) {
456 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700457 if (profileParent != null) {
458 return profileParent.id;
459 }
460 }
461 }
462
463 return userHandle;
464 }
465
466 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700467 public boolean isSameProfileGroup(int userId, int otherUserId) {
468 if (userId == otherUserId) return true;
469 checkManageUsersPermission("check if in the same profile group");
470 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700471 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700472 }
473 }
474
Fyodor Kupolov82402752015-10-28 14:54:51 -0700475 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
476 synchronized (mUsersLock) {
477 UserInfo userInfo = getUserInfoLU(userId);
478 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
479 return false;
480 }
481 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
482 if (otherUserInfo == null
483 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
484 return false;
485 }
486 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700487 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700488 }
489
490 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100491 public UserInfo getProfileParent(int userHandle) {
492 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700493 synchronized (mUsersLock) {
494 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700495 }
496 }
497
Fyodor Kupolov82402752015-10-28 14:54:51 -0700498 private UserInfo getProfileParentLU(int userHandle) {
499 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700500 if (profile == null) {
501 return null;
502 }
503 int parentUserId = profile.profileGroupId;
504 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
505 return null;
506 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700507 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100508 }
509 }
510
Fyodor Kupolov82402752015-10-28 14:54:51 -0700511 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100512 return user.id == profile.id ||
513 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
514 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000515 }
516
517 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100518 public void setUserEnabled(int userId) {
519 checkManageUsersPermission("enable user");
520 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700521 UserInfo info;
522 synchronized (mUsersLock) {
523 info = getUserInfoLU(userId);
524 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100525 if (info != null && !info.isEnabled()) {
526 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700527 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100528 }
529 }
530 }
531
532 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700533 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700534 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700535 synchronized (mUsersLock) {
536 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700537 }
538 }
539
Amith Yamasani71e6c692013-03-24 17:39:28 -0700540 @Override
541 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700542 synchronized (mUsersLock) {
543 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700544 }
545 }
546
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700547 @Override
548 public boolean canHaveRestrictedProfile(int userId) {
549 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700550 synchronized (mUsersLock) {
551 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700552 if (userInfo == null || !userInfo.canHaveProfile()) {
553 return false;
554 }
555 if (!userInfo.isAdmin()) {
556 return false;
557 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800558 // restricted profile can be created if there is no DO set and the admin user has no PO;
559 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700560 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700561 }
562
Amith Yamasani195263742012-08-21 15:40:12 -0700563 /*
564 * Should be locked on mUsers before calling this.
565 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700566 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700567 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700568 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800569 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700570 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
571 return null;
572 }
573 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700574 }
575
Fyodor Kupolov82402752015-10-28 14:54:51 -0700576 /**
577 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
578 * <p>No permissions checking or any addition checks are made</p>
579 */
580 private UserInfo getUserInfoNoChecks(int userId) {
581 synchronized (mUsersLock) {
582 return mUsers.get(userId);
583 }
584 }
585
Amith Yamasani236b2b52015-08-18 14:32:14 -0700586 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700587 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700588 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700589 }
590
Amith Yamasani258848d2012-08-10 17:06:33 -0700591 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700592 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700593 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700594 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700595 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700596 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700597 if (info == null || info.partial) {
598 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
599 return;
600 }
Amith Yamasani13593602012-03-22 16:16:17 -0700601 if (name != null && !name.equals(info.name)) {
602 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700603 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700604 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700605 }
606 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700607 if (changed) {
608 sendUserInfoChangedBroadcast(userId);
609 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700610 }
611
Amith Yamasani258848d2012-08-10 17:06:33 -0700612 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700613 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700614 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400615 long ident = Binder.clearCallingIdentity();
616 try {
617 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700618 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400619 if (info == null || info.partial) {
620 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
621 return;
622 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700623 writeBitmapLP(info, bitmap);
624 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700625 }
Jason Monk9a944532014-07-08 09:31:21 -0400626 sendUserInfoChangedBroadcast(userId);
627 } finally {
628 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700629 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700630 }
631
632 private void sendUserInfoChangedBroadcast(int userId) {
633 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
634 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
635 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700636 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700637 }
638
Amith Yamasani258848d2012-08-10 17:06:33 -0700639 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100640 public ParcelFileDescriptor getUserIcon(int userId) {
641 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700642 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700643 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700644 if (info == null || info.partial) {
645 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
646 return null;
647 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700648 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100649 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
650 || callingGroupId != info.profileGroupId) {
651 checkManageUsersPermission("get the icon of a user who is not related");
652 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700653 if (info.iconPath == null) {
654 return null;
655 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100656 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700657 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100658
659 try {
660 return ParcelFileDescriptor.open(
661 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
662 } catch (FileNotFoundException e) {
663 Log.e(LOG_TAG, "Couldn't find icon file", e);
664 }
665 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700666 }
667
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700668 public void makeInitialized(int userId) {
669 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800670 boolean scheduleWriteUser = false;
671 UserInfo info;
672 synchronized (mUsersLock) {
673 info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700674 if (info == null || info.partial) {
675 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800676 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700677 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800678 if ((info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700679 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800680 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700681 }
682 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800683 if (scheduleWriteUser) {
684 scheduleWriteUser(info);
685 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700686 }
687
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700688 /**
689 * If default guest restrictions haven't been initialized yet, add the basic
690 * restrictions.
691 */
692 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800693 synchronized (mGuestRestrictions) {
694 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800695 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800696 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
697 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
698 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700699 }
700 }
701
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800702 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530703 public Bundle getDefaultGuestRestrictions() {
704 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800705 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530706 return new Bundle(mGuestRestrictions);
707 }
708 }
709
710 @Override
711 public void setDefaultGuestRestrictions(Bundle restrictions) {
712 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800713 synchronized (mGuestRestrictions) {
714 mGuestRestrictions.clear();
715 mGuestRestrictions.putAll(restrictions);
716 }
717 synchronized (mPackagesLock) {
718 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530719 }
720 }
721
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800722 /**
723 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
724 */
725 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
726 @Nullable Bundle global) {
727 Preconditions.checkNotNull(local);
728 boolean globalChanged = false;
729 boolean localChanged;
730 synchronized (mRestrictionsLock) {
731 if (global != null) {
732 // Update global.
733 globalChanged = !UserRestrictionsUtils.areEqual(
734 mDevicePolicyGlobalUserRestrictions, global);
735 if (globalChanged) {
736 mDevicePolicyGlobalUserRestrictions = global;
737 }
738 }
739 {
740 // Update local.
741 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
742 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
743 if (localChanged) {
744 mDevicePolicyLocalUserRestrictions.put(userId, local);
745 }
746 }
747 }
748 if (DBG) {
749 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
750 + " global=" + global + (globalChanged ? " (changed)" : "")
751 + " local=" + local + (localChanged ? " (changed)" : "")
752 );
753 }
754 // Don't call them within the mRestrictionsLock.
755 synchronized (mPackagesLock) {
756 if (globalChanged) {
757 writeUserListLP();
758 }
759 if (localChanged) {
760 writeUserLP(getUserInfoNoChecks(userId));
761 }
762 }
763
764 synchronized (mRestrictionsLock) {
765 if (globalChanged) {
766 applyUserRestrictionsForAllUsersLR();
767 } else if (localChanged) {
768 applyUserRestrictionsLR(userId);
769 }
770 }
771 }
772
Makoto Onuki068c54a2015-10-13 14:34:03 -0700773 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700774 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800775 final Bundle baseRestrictions =
776 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
777 final Bundle global = mDevicePolicyGlobalUserRestrictions;
778 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700779
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800780 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
781 // Common case first.
782 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700783 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800784 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
785 UserRestrictionsUtils.merge(effective, global);
786 UserRestrictionsUtils.merge(effective, local);
787
Makoto Onuki068c54a2015-10-13 14:34:03 -0700788 return effective;
789 }
790
791 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700792 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700793 if (DBG) {
794 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
795 }
796 mCachedEffectiveUserRestrictions.remove(userId);
797 }
798
799 private Bundle getEffectiveUserRestrictions(int userId) {
800 synchronized (mRestrictionsLock) {
801 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
802 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700803 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700804 mCachedEffectiveUserRestrictions.put(userId, restrictions);
805 }
806 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700807 }
808 }
809
Makoto Onuki068c54a2015-10-13 14:34:03 -0700810 /** @return a specific user restriction that's in effect currently. */
811 @Override
812 public boolean hasUserRestriction(String restrictionKey, int userId) {
813 Bundle restrictions = getEffectiveUserRestrictions(userId);
814 return restrictions != null && restrictions.getBoolean(restrictionKey);
815 }
816
817 /**
818 * @return UserRestrictions that are in effect currently. This always returns a new
819 * {@link Bundle}.
820 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700821 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800822 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800823 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800824 }
825
826 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700827 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700828 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700829 synchronized (mRestrictionsLock) {
830 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
831 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800832 final Bundle newRestrictions = UserRestrictionsUtils.clone(
833 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700834 newRestrictions.putBoolean(key, value);
835
Fyodor Kupolov82402752015-10-28 14:54:51 -0700836 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700837 }
838 }
839
Makoto Onuki068c54a2015-10-13 14:34:03 -0700840 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800841 * Optionally updating user restrictions, calculate the effective user restrictions and also
842 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700843 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800844 * @param newRestrictions User restrictions to set.
845 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700846 * @param userId target user ID.
847 */
848 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700849 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700850 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800851
852 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
853 mAppliedUserRestrictions.get(userId));
854
855 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700856 if (newRestrictions != null) {
857 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800858 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
859
860 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700861 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
862 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800863
864 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
865 mBaseUserRestrictions.put(userId, newRestrictions);
866 scheduleWriteUser(getUserInfoNoChecks(userId));
867 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700868 }
869
Fyodor Kupolov82402752015-10-28 14:54:51 -0700870 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700871
Makoto Onuki759a7632015-10-28 16:43:10 -0700872 mCachedEffectiveUserRestrictions.put(userId, effective);
873
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800874 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700875 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800876 debug("Applying user restrictions: userId=" + userId
877 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700878 }
879
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800880 if (mAppOpsService != null) { // We skip it until system-ready.
881 final long token = Binder.clearCallingIdentity();
882 try {
883 mAppOpsService.setUserRestrictions(effective, userId);
884 } catch (RemoteException e) {
885 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
886 } finally {
887 Binder.restoreCallingIdentity(token);
888 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700889 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700890
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800891 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700892
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800893 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700894 }
895
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800896 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800897 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800898 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
899 // actually, but we still need some kind of synchronization otherwise we might end up
900 // calling listeners out-of-order, thus "LR".
901
902 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
903 return;
904 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800905
906 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
907 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
908
909 mHandler.post(new Runnable() {
910 @Override
911 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700912 UserRestrictionsUtils.applyUserRestrictions(
913 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800914
Makoto Onukid45a4a22015-11-02 17:17:38 -0800915 final UserRestrictionsListener[] listeners;
916 synchronized (mUserRestrictionsListeners) {
917 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
918 mUserRestrictionsListeners.toArray(listeners);
919 }
920 for (int i = 0; i < listeners.length; i++) {
921 listeners[i].onUserRestrictionsChanged(userId,
922 newRestrictionsFinal, prevRestrictionsFinal);
923 }
924 }
925 });
926 }
927
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800928 // Package private for the inner class.
929 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700930 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700931 }
932
933 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800934 // Package private for the inner class.
935 void applyUserRestrictionsForAllUsersLR() {
936 if (DBG) {
937 debug("applyUserRestrictionsForAllUsersLR");
938 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700939 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700940 mCachedEffectiveUserRestrictions.clear();
941
Makoto Onuki068c54a2015-10-13 14:34:03 -0700942 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
943 // it on a handler.
944 final Runnable r = new Runnable() {
945 @Override
946 public void run() {
947 // Then get the list of running users.
948 final int[] runningUsers;
949 try {
950 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
951 } catch (RemoteException e) {
952 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
953 return;
954 }
955 // Then re-calculate the effective restrictions and apply, only for running users.
956 // It's okay if a new user has started after the getRunningUserIds() call,
957 // because we'll do the same thing (re-calculate the restrictions and apply)
958 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700959 synchronized (mRestrictionsLock) {
960 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800961 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700962 }
963 }
964 }
965 };
966 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700967 }
968
Amith Yamasani258848d2012-08-10 17:06:33 -0700969 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700970 * Check if we've hit the limit of how many users can be created.
971 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700972 private boolean isUserLimitReached() {
973 int count;
974 synchronized (mUsersLock) {
975 count = getAliveUsersExcludingGuestsCountLU();
976 }
977 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700978 }
979
980 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000981 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700982 checkManageUsersPermission("check if more managed profiles can be added.");
983 if (ActivityManager.isLowRamDeviceStatic()) {
984 return false;
985 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700986 if (!mContext.getPackageManager().hasSystemFeature(
987 PackageManager.FEATURE_MANAGED_USERS)) {
988 return false;
989 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100990 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000991 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
992 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
993 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100994 return false;
995 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700996 synchronized(mUsersLock) {
997 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100998 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700999 return false;
1000 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001001 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1002 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001003 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001004 return usersCountAfterRemoving == 1
1005 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001006 }
1007 }
1008
Fyodor Kupolov82402752015-10-28 14:54:51 -07001009 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001010 int aliveUserCount = 0;
1011 final int totalUserCount = mUsers.size();
1012 // Skip over users being removed
1013 for (int i = 0; i < totalUserCount; i++) {
1014 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001015 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001016 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001017 aliveUserCount++;
1018 }
1019 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001020 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001021 }
1022
1023 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001024 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001025 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1026 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1027 * permissions can make certain calls to the UserManager.
1028 *
1029 * @param message used as message if SecurityException is thrown
1030 * @throws SecurityException if the caller does not have enough privilege.
1031 */
1032 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1033 final int uid = Binder.getCallingUid();
1034 if (uid != Process.SYSTEM_UID && uid != 0
1035 && ActivityManager.checkComponentPermission(
1036 Manifest.permission.MANAGE_USERS,
1037 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1038 && ActivityManager.checkComponentPermission(
1039 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1040 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1041 throw new SecurityException(
1042 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1043 + message);
1044 }
1045 }
1046
1047 /**
1048 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001049 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001050 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001051 *
1052 * @param message used as message if SecurityException is thrown
1053 * @throws SecurityException if the caller is not system or root
1054 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001055 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001056 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -07001057 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001058 && ActivityManager.checkComponentPermission(
1059 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001060 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1061 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1062 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001063 }
1064
Fyodor Kupolov82402752015-10-28 14:54:51 -07001065 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001066 try {
1067 File dir = new File(mUsersDir, Integer.toString(info.id));
1068 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001069 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001070 if (!dir.exists()) {
1071 dir.mkdir();
1072 FileUtils.setPermissions(
1073 dir.getPath(),
1074 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1075 -1, -1);
1076 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001077 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001078 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1079 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001080 info.iconPath = file.getAbsolutePath();
1081 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001082 try {
1083 os.close();
1084 } catch (IOException ioe) {
1085 // What the ... !
1086 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001087 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001088 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001089 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001090 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001091 }
1092
Amith Yamasani0b285492011-04-14 17:35:23 -07001093 /**
1094 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1095 * cache it elsewhere.
1096 * @return the array of user ids.
1097 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001098 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001099 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001100 return mUserIds;
1101 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001102 }
1103
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001104 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001105 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001106 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001107 return;
1108 }
1109 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001110 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001111 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001112 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001113 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001114 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001115 int type;
1116 while ((type = parser.next()) != XmlPullParser.START_TAG
1117 && type != XmlPullParser.END_DOCUMENT) {
1118 ;
1119 }
1120
1121 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001122 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001123 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001124 return;
1125 }
1126
Amith Yamasani2a003292012-08-14 18:25:45 -07001127 mNextSerialNumber = -1;
1128 if (parser.getName().equals(TAG_USERS)) {
1129 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1130 if (lastSerialNumber != null) {
1131 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1132 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001133 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1134 if (versionNumber != null) {
1135 mUserVersion = Integer.parseInt(versionNumber);
1136 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001137 }
1138
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001139 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1140
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001141 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301142 if (type == XmlPullParser.START_TAG) {
1143 final String name = parser.getName();
1144 if (name.equals(TAG_USER)) {
1145 String id = parser.getAttributeValue(null, ATTR_ID);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001146 Pair<UserInfo, String> userPair = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001147
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001148 if (userPair != null) {
1149 UserInfo user = userPair.first;
1150 String account = userPair.second;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001151 synchronized (mUsersLock) {
1152 mUsers.put(user.id, user);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001153 mUserAccounts.put(user.id, account);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001154 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1155 mNextSerialNumber = user.id + 1;
1156 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301157 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001158 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301159 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001160 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1161 && type != XmlPullParser.END_TAG) {
1162 if (type == XmlPullParser.START_TAG) {
1163 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001164 synchronized (mGuestRestrictions) {
1165 UserRestrictionsUtils
1166 .readRestrictions(parser, mGuestRestrictions);
1167 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001168 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1169 ) {
1170 UserRestrictionsUtils.readRestrictions(parser,
1171 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001172 }
1173 break;
1174 }
1175 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001176 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001177 }
1178 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001179 synchronized (mRestrictionsLock) {
1180 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1181 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001182 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001183 upgradeIfNecessaryLP();
1184 } catch (IOException | XmlPullParserException e) {
1185 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001186 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001187 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001188 }
1189 }
1190
Amith Yamasani6f34b412012-10-22 18:19:27 -07001191 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001192 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001193 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001194 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001195 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001196 int userVersion = mUserVersion;
1197 if (userVersion < 1) {
1198 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001199 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001200 if ("Primary".equals(user.name)) {
1201 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001202 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001203 }
1204 userVersion = 1;
1205 }
1206
Amith Yamasanibc9625052012-11-15 14:39:18 -08001207 if (userVersion < 2) {
1208 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001209 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001210 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1211 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001212 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001213 }
1214 userVersion = 2;
1215 }
1216
Amith Yamasani350962c2013-08-06 11:18:53 -07001217
Amith Yamasani5e486f52013-08-07 11:06:44 -07001218 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001219 userVersion = 4;
1220 }
1221
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001222 if (userVersion < 5) {
1223 initDefaultGuestRestrictions();
1224 userVersion = 5;
1225 }
1226
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001227 if (userVersion < 6) {
1228 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001229 synchronized (mUsersLock) {
1230 for (int i = 0; i < mUsers.size(); i++) {
1231 UserInfo user = mUsers.valueAt(i);
1232 // In non-split mode, only user 0 can have restricted profiles
1233 if (!splitSystemUser && user.isRestricted()
1234 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1235 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001236 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001237 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001238 }
1239 }
1240 userVersion = 6;
1241 }
1242
Amith Yamasani6f34b412012-10-22 18:19:27 -07001243 if (userVersion < USER_VERSION) {
1244 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1245 + USER_VERSION);
1246 } else {
1247 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001248
1249 if (originalVersion < mUserVersion) {
1250 writeUserListLP();
1251 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001252 }
1253 }
1254
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001255 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001256 int flags = UserInfo.FLAG_INITIALIZED;
1257 // In split system user mode, the admin and primary flags are assigned to the first human
1258 // user.
1259 if (!UserManager.isSplitSystemUser()) {
1260 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1261 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001262 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001263 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001264 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001265 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001266 synchronized (mUsersLock) {
1267 mUsers.put(system.id, system);
1268 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001269 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001270 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001271
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001272 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001273 synchronized (mRestrictionsLock) {
1274 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1275 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001276
Fyodor Kupolov82402752015-10-28 14:54:51 -07001277 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001278 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001279
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001280 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001281 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001282 }
1283
Makoto Onuki9e935a32015-11-06 14:24:24 -08001284 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001285 if (DBG) {
1286 debug("scheduleWriteUser");
1287 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001288 // No need to wrap it within a lock -- worst case, we'll just post the same message
1289 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001290 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1291 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1292 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1293 }
1294 }
1295
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001296 /*
1297 * Writes the user file in this format:
1298 *
1299 * <user flags="20039023" id="0">
1300 * <name>Primary</name>
1301 * </user>
1302 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001303 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001304 if (DBG) {
1305 debug("writeUserLP " + userInfo);
1306 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001307 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001308 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001309 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001310 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001311 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1312
1313 // XmlSerializer serializer = XmlUtils.serializerInstance();
1314 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001315 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001316 serializer.startDocument(null, true);
1317 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1318
1319 serializer.startTag(null, TAG_USER);
1320 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001321 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001322 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001323 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1324 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1325 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001326 if (userInfo.iconPath != null) {
1327 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1328 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001329 if (userInfo.partial) {
1330 serializer.attribute(null, ATTR_PARTIAL, "true");
1331 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001332 if (userInfo.guestToRemove) {
1333 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1334 }
Kenny Guy2a764942014-04-02 13:29:20 +01001335 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1336 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1337 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001338 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001339 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1340 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1341 Integer.toString(userInfo.restrictedProfileParentId));
1342 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001343 serializer.startTag(null, TAG_NAME);
1344 serializer.text(userInfo.name);
1345 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001346 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001347 UserRestrictionsUtils.writeRestrictions(serializer,
1348 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1349 UserRestrictionsUtils.writeRestrictions(serializer,
1350 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1351 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001352 }
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001353 // Update the account field if it is set.
1354 String account;
1355 synchronized (mUsersLock) {
1356 account = mUserAccounts.get(userInfo.id);
1357 }
1358 if (account != null) {
1359 serializer.startTag(null, TAG_ACCOUNT);
1360 serializer.text(account);
1361 serializer.endTag(null, TAG_ACCOUNT);
1362 }
1363
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001364 serializer.endTag(null, TAG_USER);
1365
1366 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001367 userFile.finishWrite(fos);
1368 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001369 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001370 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001371 }
1372 }
1373
1374 /*
1375 * Writes the user list file in this format:
1376 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001377 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001378 * <user id="0"></user>
1379 * <user id="2"></user>
1380 * </users>
1381 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001382 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001383 if (DBG) {
1384 debug("writeUserList");
1385 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001386 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001387 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001388 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001389 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001390 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1391
1392 // XmlSerializer serializer = XmlUtils.serializerInstance();
1393 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001394 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001395 serializer.startDocument(null, true);
1396 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1397
1398 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001399 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001400 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001401
Adam Lesinskieddeb492014-09-08 17:50:03 -07001402 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001403 synchronized (mGuestRestrictions) {
1404 UserRestrictionsUtils
1405 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1406 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301407 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001408 synchronized (mRestrictionsLock) {
1409 UserRestrictionsUtils.writeRestrictions(serializer,
1410 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1411 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001412 int[] userIdsToWrite;
1413 synchronized (mUsersLock) {
1414 userIdsToWrite = new int[mUsers.size()];
1415 for (int i = 0; i < userIdsToWrite.length; i++) {
1416 UserInfo user = mUsers.valueAt(i);
1417 userIdsToWrite[i] = user.id;
1418 }
1419 }
1420 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001421 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001422 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001423 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001424 }
1425
1426 serializer.endTag(null, TAG_USERS);
1427
1428 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001429 userListFile.finishWrite(fos);
1430 } catch (Exception e) {
1431 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001432 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001433 }
1434 }
1435
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001436 private Pair<UserInfo, String> readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001437 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001438 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001439 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001440 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001441 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001442 long creationTime = 0L;
1443 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001444 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001445 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001446 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001447 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001448 Bundle baseRestrictions = new Bundle();
1449 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001450
1451 FileInputStream fis = null;
1452 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001453 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001454 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001455 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001456 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001457 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001458 int type;
1459 while ((type = parser.next()) != XmlPullParser.START_TAG
1460 && type != XmlPullParser.END_DOCUMENT) {
1461 ;
1462 }
1463
1464 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001465 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001466 return null;
1467 }
1468
1469 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001470 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1471 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001472 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001473 return null;
1474 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001475 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1476 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001477 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001478 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1479 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001480 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1481 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001482 restrictedProfileParentId = readIntAttribute(parser,
1483 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001484 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1485 if ("true".equals(valueString)) {
1486 partial = true;
1487 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001488 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1489 if ("true".equals(valueString)) {
1490 guestToRemove = true;
1491 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001492
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001493 int outerDepth = parser.getDepth();
1494 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1495 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1496 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1497 continue;
1498 }
1499 String tag = parser.getName();
1500 if (TAG_NAME.equals(tag)) {
1501 type = parser.next();
1502 if (type == XmlPullParser.TEXT) {
1503 name = parser.getText();
1504 }
1505 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001506 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1507 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1508 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001509 } else if (TAG_ACCOUNT.equals(tag)) {
1510 type = parser.next();
1511 if (type == XmlPullParser.TEXT) {
1512 account = parser.getText();
1513 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001514 }
1515 }
1516 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001517
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001518 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001519 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001520 userInfo.creationTime = creationTime;
1521 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001522 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001523 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001524 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001525 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001526 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001527 mBaseUserRestrictions.put(id, baseRestrictions);
1528 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001529 }
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001530 return new Pair<>(userInfo, account);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001531
1532 } catch (IOException ioe) {
1533 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001534 } finally {
1535 if (fis != null) {
1536 try {
1537 fis.close();
1538 } catch (IOException e) {
1539 }
1540 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001541 }
1542 return null;
1543 }
1544
Amith Yamasani920ace02012-09-20 22:15:37 -07001545 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1546 String valueString = parser.getAttributeValue(null, attr);
1547 if (valueString == null) return defaultValue;
1548 try {
1549 return Integer.parseInt(valueString);
1550 } catch (NumberFormatException nfe) {
1551 return defaultValue;
1552 }
1553 }
1554
1555 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1556 String valueString = parser.getAttributeValue(null, attr);
1557 if (valueString == null) return defaultValue;
1558 try {
1559 return Long.parseLong(valueString);
1560 } catch (NumberFormatException nfe) {
1561 return defaultValue;
1562 }
1563 }
1564
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001565 private boolean isPackageInstalled(String pkg, int userId) {
1566 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1567 PackageManager.GET_UNINSTALLED_PACKAGES,
1568 userId);
1569 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1570 return false;
1571 }
1572 return true;
1573 }
1574
Amith Yamasanib82add22013-07-09 11:24:44 -07001575 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001576 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001577 * Does not do any permissions checking.
1578 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001579 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001580 synchronized (mPackagesLock) {
1581 File dir = Environment.getUserSystemDirectory(userId);
1582 String[] files = dir.list();
1583 if (files == null) return;
1584 for (String fileName : files) {
1585 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1586 File resFile = new File(dir, fileName);
1587 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001588 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001589 }
1590 }
1591 }
1592 }
1593 }
1594
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001595 /**
1596 * Removes the app restrictions file for a specific package and user id, if it exists.
1597 */
1598 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1599 synchronized (mPackagesLock) {
1600 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001601 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001602 if (resFile.exists()) {
1603 resFile.delete();
1604 }
1605 }
1606 }
1607
Kenny Guya52dc3e2014-02-11 15:33:14 +00001608 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001609 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001610 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001611 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001612 }
1613
Amith Yamasani258848d2012-08-10 17:06:33 -07001614 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001615 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001616 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001617 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001618 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001619
Jessica Hummelbe81c802014-04-22 15:49:22 +01001620 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001621 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001622 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1623 return null;
1624 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001625 if (ActivityManager.isLowRamDeviceStatic()) {
1626 return null;
1627 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001628 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001629 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001630 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001631 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001632 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001633 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001634 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001635 synchronized (mPackagesLock) {
1636 UserInfo parent = null;
1637 if (parentId != UserHandle.USER_NULL) {
1638 synchronized (mUsersLock) {
1639 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001640 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001641 if (parent == null) return null;
1642 }
1643 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1644 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1645 return null;
1646 }
1647 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1648 // If we're not adding a guest user or a managed profile and the limit has
1649 // been reached, cannot add a user.
1650 return null;
1651 }
1652 // If we're adding a guest and there already exists one, bail.
1653 if (isGuest && findCurrentGuestUser() != null) {
1654 return null;
1655 }
1656 // In legacy mode, restricted profile's parent can only be the owner user
1657 if (isRestricted && !UserManager.isSplitSystemUser()
1658 && (parentId != UserHandle.USER_SYSTEM)) {
1659 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1660 return null;
1661 }
1662 if (isRestricted && UserManager.isSplitSystemUser()) {
1663 if (parent == null) {
1664 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1665 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001666 return null;
1667 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001668 if (!parent.canHaveProfile()) {
1669 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1670 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001671 return null;
1672 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001673 }
1674 // In split system user mode, we assign the first human user the primary flag.
1675 // And if there is no device owner, we also assign the admin flag to primary user.
1676 if (UserManager.isSplitSystemUser()
1677 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1678 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001679 synchronized (mUsersLock) {
1680 if (!mIsDeviceManaged) {
1681 flags |= UserInfo.FLAG_ADMIN;
1682 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001683 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001684 }
1685 userId = getNextAvailableId();
1686 userInfo = new UserInfo(userId, name, null, flags);
1687 userInfo.serialNumber = mNextSerialNumber++;
1688 long now = System.currentTimeMillis();
1689 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1690 userInfo.partial = true;
1691 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1692 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001693 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001694 }
1695 writeUserListLP();
1696 if (parent != null) {
1697 if (isManagedProfile) {
1698 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1699 parent.profileGroupId = parent.id;
1700 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001701 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001702 userInfo.profileGroupId = parent.profileGroupId;
1703 } else if (isRestricted) {
1704 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1705 parent.restrictedProfileParentId = parent.id;
1706 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001707 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001708 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001709 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001710 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001711 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001712 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1713 storage.createUserKey(userId, userInfo.serialNumber);
1714 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1715 final String volumeUuid = vol.getFsUuid();
1716 try {
1717 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1718 storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
1719 enforceSerialNumber(userDir, userInfo.serialNumber);
1720 } catch (IOException e) {
1721 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1722 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001723 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001724 mPm.createNewUser(userId);
1725 userInfo.partial = false;
1726 synchronized (mPackagesLock) {
1727 writeUserLP(userInfo);
1728 }
1729 updateUserIds();
1730 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001731 if (isGuest) {
1732 synchronized (mGuestRestrictions) {
1733 restrictions.putAll(mGuestRestrictions);
1734 }
1735 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001736 synchronized (mRestrictionsLock) {
1737 mBaseUserRestrictions.append(userId, restrictions);
1738 }
1739 mPm.newUserCreated(userId);
1740 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1741 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1742 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1743 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001744 } finally {
1745 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001746 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001747 return userInfo;
1748 }
1749
Amith Yamasani0b285492011-04-14 17:35:23 -07001750 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001751 * @hide
1752 */
1753 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1754 checkManageUsersPermission("setupRestrictedProfile");
1755 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1756 if (user == null) {
1757 return null;
1758 }
1759 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1760 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1761 // the putIntForUser() will fail.
1762 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1763 android.provider.Settings.Secure.LOCATION_MODE,
1764 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1765 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1766 return user;
1767 }
1768
1769 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001770 * Find the current guest user. If the Guest user is partial,
1771 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001772 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001773 private UserInfo findCurrentGuestUser() {
1774 synchronized (mUsersLock) {
1775 final int size = mUsers.size();
1776 for (int i = 0; i < size; i++) {
1777 final UserInfo user = mUsers.valueAt(i);
1778 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1779 return user;
1780 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001781 }
1782 }
1783 return null;
1784 }
1785
1786 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001787 * Mark this guest user for deletion to allow us to create another guest
1788 * and switch to that user before actually removing this guest.
1789 * @param userHandle the userid of the current guest
1790 * @return whether the user could be marked for deletion
1791 */
1792 public boolean markGuestForDeletion(int userHandle) {
1793 checkManageUsersPermission("Only the system can remove users");
1794 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1795 UserManager.DISALLOW_REMOVE_USER, false)) {
1796 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1797 return false;
1798 }
1799
1800 long ident = Binder.clearCallingIdentity();
1801 try {
1802 final UserInfo user;
1803 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001804 synchronized (mUsersLock) {
1805 user = mUsers.get(userHandle);
1806 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1807 return false;
1808 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001809 }
1810 if (!user.isGuest()) {
1811 return false;
1812 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001813 // We set this to a guest user that is to be removed. This is a temporary state
1814 // where we are allowed to add new Guest users, even if this one is still not
1815 // removed. This user will still show up in getUserInfo() calls.
1816 // If we don't get around to removing this Guest user, it will be purged on next
1817 // startup.
1818 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001819 // Mark it as disabled, so that it isn't returned any more when
1820 // profiles are queried.
1821 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001822 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001823 }
1824 } finally {
1825 Binder.restoreCallingIdentity(ident);
1826 }
1827 return true;
1828 }
1829
1830 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001831 * Removes a user and all data directories created for that user. This method should be called
1832 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001833 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001834 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001835 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001836 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001837 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1838 UserManager.DISALLOW_REMOVE_USER, false)) {
1839 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1840 return false;
1841 }
1842
Kenny Guyee58b4f2014-05-23 15:19:53 +01001843 long ident = Binder.clearCallingIdentity();
1844 try {
1845 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001846 int currentUser = ActivityManager.getCurrentUser();
1847 if (currentUser == userHandle) {
1848 Log.w(LOG_TAG, "Current user cannot be removed");
1849 return false;
1850 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001851 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001852 synchronized (mUsersLock) {
1853 user = mUsers.get(userHandle);
1854 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1855 return false;
1856 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001857
Fyodor Kupolov82402752015-10-28 14:54:51 -07001858 // We remember deleted user IDs to prevent them from being
1859 // reused during the current boot; they can still be reused
1860 // after a reboot.
1861 mRemovingUserIds.put(userHandle, true);
1862 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001863
Kenny Guyee58b4f2014-05-23 15:19:53 +01001864 try {
1865 mAppOpsService.removeUser(userHandle);
1866 } catch (RemoteException e) {
1867 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1868 }
1869 // Set this to a partially created user, so that the user will be purged
1870 // on next startup, in case the runtime stops now before stopping and
1871 // removing the user completely.
1872 user.partial = true;
1873 // Mark it as disabled, so that it isn't returned any more when
1874 // profiles are queried.
1875 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001876 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001877 }
1878
1879 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1880 && user.isManagedProfile()) {
1881 // Send broadcast to notify system that the user removed was a
1882 // managed user.
1883 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1884 }
1885
1886 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1887 int res;
1888 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001889 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
1890 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001891 @Override
1892 public void userStopped(int userId) {
1893 finishRemoveUser(userId);
1894 }
1895 @Override
1896 public void userStopAborted(int userId) {
1897 }
1898 });
1899 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001900 return false;
1901 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001902 return res == ActivityManager.USER_OP_SUCCESS;
1903 } finally {
1904 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001905 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001906 }
1907
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001908 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001909 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001910 // Let other services shutdown any activity and clean up their state before completely
1911 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001912 long ident = Binder.clearCallingIdentity();
1913 try {
1914 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1915 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001916 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1917 android.Manifest.permission.MANAGE_USERS,
1918
1919 new BroadcastReceiver() {
1920 @Override
1921 public void onReceive(Context context, Intent intent) {
1922 if (DBG) {
1923 Slog.i(LOG_TAG,
1924 "USER_REMOVED broadcast sent, cleaning up user data "
1925 + userHandle);
1926 }
1927 new Thread() {
1928 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001929 // Clean up any ActivityManager state
1930 LocalServices.getService(ActivityManagerInternal.class)
1931 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001932 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001933 }
1934 }.start();
1935 }
1936 },
1937
1938 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001939 } finally {
1940 Binder.restoreCallingIdentity(ident);
1941 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001942 }
1943
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001944 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001945 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001946 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001947 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001948
1949 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001950 synchronized (mUsersLock) {
1951 mUsers.remove(userHandle);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001952 mUserAccounts.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08001953 mIsUserManaged.delete(userHandle);
1954 }
1955 synchronized (mRestrictionsLock) {
1956 mBaseUserRestrictions.remove(userHandle);
1957 mAppliedUserRestrictions.remove(userHandle);
1958 mCachedEffectiveUserRestrictions.remove(userHandle);
1959 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001960 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001961 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001962 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001963 userFile.delete();
1964 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001965 synchronized (mPackagesLock) {
1966 writeUserListLP();
1967 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001968 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001969 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1970 }
1971
Amith Yamasani61f57372012-08-31 12:12:28 -07001972 private void removeDirectoryRecursive(File parent) {
1973 if (parent.isDirectory()) {
1974 String[] files = parent.list();
1975 for (String filename : files) {
1976 File child = new File(parent, filename);
1977 removeDirectoryRecursive(child);
1978 }
1979 }
1980 parent.delete();
1981 }
1982
Kenny Guyf8d3a232014-05-15 16:09:52 +01001983 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001984 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001985 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1986 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001987 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1988 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001989 }
1990
Amith Yamasani2a003292012-08-14 18:25:45 -07001991 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001992 public Bundle getApplicationRestrictions(String packageName) {
1993 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1994 }
1995
1996 @Override
1997 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001998 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001999 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01002000 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002001 }
2002 synchronized (mPackagesLock) {
2003 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002004 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002005 }
2006 }
2007
2008 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002009 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002010 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01002011 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002012 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002013 if (restrictions == null || restrictions.isEmpty()) {
2014 cleanAppRestrictionsForPackage(packageName, userId);
2015 } else {
2016 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002017 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002018 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002019 }
Robin Lee66e5d962014-04-09 16:44:21 +01002020
Kenny Guyd21b2182014-07-17 16:38:55 +01002021 if (isPackageInstalled(packageName, userId)) {
2022 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2023 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2024 changeIntent.setPackage(packageName);
2025 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2026 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2027 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002028 }
2029
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002030 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002031 mHandler.post(new Runnable() {
2032 @Override
2033 public void run() {
2034 List<ApplicationInfo> apps =
2035 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
2036 userHandle).getList();
2037 final long ident = Binder.clearCallingIdentity();
2038 try {
2039 for (ApplicationInfo appInfo : apps) {
2040 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002041 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
2042 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002043 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002044 userHandle);
2045 }
2046 }
2047 } finally {
2048 Binder.restoreCallingIdentity(ident);
2049 }
2050 }
2051 });
2052 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002053 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002054 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002055 try {
2056 return mContext.getPackageManager().getApplicationInfo(packageName,
2057 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2058 } catch (NameNotFoundException nnfe) {
2059 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002060 } finally {
2061 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002062 }
2063 }
2064
Fyodor Kupolov82402752015-10-28 14:54:51 -07002065 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002066 AtomicFile restrictionsFile =
2067 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2068 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002069 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002070 }
2071
2072 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002073 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002074 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002075 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002076 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002077 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002078 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002079
2080 FileInputStream fis = null;
2081 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002082 fis = restrictionsFile.openRead();
2083 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002084 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002085 XmlUtils.nextElement(parser);
2086 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002087 Slog.e(LOG_TAG, "Unable to read restrictions file "
2088 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002089 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002090 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002091 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2092 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002093 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002094 } catch (IOException|XmlPullParserException e) {
2095 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002096 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002097 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002098 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002099 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002100 }
2101
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002102 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2103 XmlPullParser parser) throws XmlPullParserException, IOException {
2104 int type = parser.getEventType();
2105 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2106 String key = parser.getAttributeValue(null, ATTR_KEY);
2107 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2108 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2109 if (multiple != null) {
2110 values.clear();
2111 int count = Integer.parseInt(multiple);
2112 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2113 if (type == XmlPullParser.START_TAG
2114 && parser.getName().equals(TAG_VALUE)) {
2115 values.add(parser.nextText().trim());
2116 count--;
2117 }
2118 }
2119 String [] valueStrings = new String[values.size()];
2120 values.toArray(valueStrings);
2121 restrictions.putStringArray(key, valueStrings);
2122 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2123 restrictions.putBundle(key, readBundleEntry(parser, values));
2124 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2125 final int outerDepth = parser.getDepth();
2126 ArrayList<Bundle> bundleList = new ArrayList<>();
2127 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2128 Bundle childBundle = readBundleEntry(parser, values);
2129 bundleList.add(childBundle);
2130 }
2131 restrictions.putParcelableArray(key,
2132 bundleList.toArray(new Bundle[bundleList.size()]));
2133 } else {
2134 String value = parser.nextText().trim();
2135 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2136 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2137 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2138 restrictions.putInt(key, Integer.parseInt(value));
2139 } else {
2140 restrictions.putString(key, value);
2141 }
2142 }
2143 }
2144 }
2145
2146 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2147 throws IOException, XmlPullParserException {
2148 Bundle childBundle = new Bundle();
2149 final int outerDepth = parser.getDepth();
2150 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2151 readEntry(childBundle, values, parser);
2152 }
2153 return childBundle;
2154 }
2155
Fyodor Kupolov82402752015-10-28 14:54:51 -07002156 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002157 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002158 AtomicFile restrictionsFile = new AtomicFile(
2159 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002160 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002161 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002162 }
2163
2164 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002165 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002166 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002167 try {
2168 fos = restrictionsFile.startWrite();
2169 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2170
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002171 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002172 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002173 serializer.startDocument(null, true);
2174 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2175
2176 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002177 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002178 serializer.endTag(null, TAG_RESTRICTIONS);
2179
2180 serializer.endDocument();
2181 restrictionsFile.finishWrite(fos);
2182 } catch (Exception e) {
2183 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002184 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2185 }
2186 }
2187
2188 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2189 throws IOException {
2190 for (String key : restrictions.keySet()) {
2191 Object value = restrictions.get(key);
2192 serializer.startTag(null, TAG_ENTRY);
2193 serializer.attribute(null, ATTR_KEY, key);
2194
2195 if (value instanceof Boolean) {
2196 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2197 serializer.text(value.toString());
2198 } else if (value instanceof Integer) {
2199 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2200 serializer.text(value.toString());
2201 } else if (value == null || value instanceof String) {
2202 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2203 serializer.text(value != null ? (String) value : "");
2204 } else if (value instanceof Bundle) {
2205 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2206 writeBundle((Bundle) value, serializer);
2207 } else if (value instanceof Parcelable[]) {
2208 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2209 Parcelable[] array = (Parcelable[]) value;
2210 for (Parcelable parcelable : array) {
2211 if (!(parcelable instanceof Bundle)) {
2212 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2213 }
2214 serializer.startTag(null, TAG_ENTRY);
2215 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2216 writeBundle((Bundle) parcelable, serializer);
2217 serializer.endTag(null, TAG_ENTRY);
2218 }
2219 } else {
2220 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2221 String[] values = (String[]) value;
2222 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2223 for (String choice : values) {
2224 serializer.startTag(null, TAG_VALUE);
2225 serializer.text(choice != null ? choice : "");
2226 serializer.endTag(null, TAG_VALUE);
2227 }
2228 }
2229 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002230 }
2231 }
2232
2233 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002234 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002235 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002236 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002237 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002238 }
2239 }
2240
2241 @Override
2242 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002243 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002244 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002245 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002246 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002247 }
2248 // Not found
2249 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002250 }
2251 }
2252
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002253 @Override
2254 public long getUserCreationTime(int userHandle) {
2255 int callingUserId = UserHandle.getCallingUserId();
2256 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002257 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002258 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002259 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002260 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002261 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002262 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002263 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002264 }
2265 }
2266 }
2267 if (userInfo == null) {
2268 throw new SecurityException("userHandle can only be the calling user or a managed "
2269 + "profile associated with this user");
2270 }
2271 return userInfo.creationTime;
2272 }
2273
Amith Yamasani0b285492011-04-14 17:35:23 -07002274 /**
2275 * Caches the list of user ids in an array, adjusting the array size when necessary.
2276 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002277 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002278 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002279 synchronized (mUsersLock) {
2280 final int userSize = mUsers.size();
2281 for (int i = 0; i < userSize; i++) {
2282 if (!mUsers.valueAt(i).partial) {
2283 num++;
2284 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002285 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002286 final int[] newUsers = new int[num];
2287 int n = 0;
2288 for (int i = 0; i < userSize; i++) {
2289 if (!mUsers.valueAt(i).partial) {
2290 newUsers[n++] = mUsers.keyAt(i);
2291 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002292 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002293 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002294 }
2295 }
2296
2297 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002298 * Called right before a user starts. This will not be called for the system user.
2299 */
2300 public void onBeforeStartUser(int userId) {
2301 synchronized (mRestrictionsLock) {
2302 applyUserRestrictionsLR(userId);
2303 }
2304 }
2305
2306 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002307 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002308 * @param userId the user that was just foregrounded
2309 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002310 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002311 UserInfo user = getUserInfoNoChecks(userId);
2312 if (user == null || user.partial) {
2313 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2314 return;
2315 }
2316 long now = System.currentTimeMillis();
2317 if (now > EPOCH_PLUS_30_YEARS) {
2318 user.lastLoggedInTime = now;
2319 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002320 }
2321 }
2322
2323 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002324 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002325 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2326 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002327 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002328 private int getNextAvailableId() {
2329 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002330 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002331 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002332 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002333 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002334 }
2335 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002336 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002337 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002338 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002339 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002340
Amith Yamasanifc95e702013-09-26 13:20:17 -07002341 private String packageToRestrictionsFileName(String packageName) {
2342 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2343 }
2344
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002345 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002346 * Enforce that serial number stored in user directory inode matches the
2347 * given expected value. Gracefully sets the serial number if currently
2348 * undefined.
2349 *
2350 * @throws IOException when problem extracting serial number, or serial
2351 * number is mismatched.
2352 */
2353 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2354 final int foundSerial = getSerialNumber(file);
2355 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2356
2357 if (foundSerial == -1) {
2358 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2359 try {
2360 setSerialNumber(file, serialNumber);
2361 } catch (IOException e) {
2362 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2363 }
2364
2365 } else if (foundSerial != serialNumber) {
2366 throw new IOException("Found serial number " + foundSerial
2367 + " doesn't match expected " + serialNumber);
2368 }
2369 }
2370
2371 /**
2372 * Set serial number stored in user directory inode.
2373 *
2374 * @throws IOException if serial number was already set
2375 */
2376 private static void setSerialNumber(File file, int serialNumber)
2377 throws IOException {
2378 try {
2379 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2380 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2381 } catch (ErrnoException e) {
2382 throw e.rethrowAsIOException();
2383 }
2384 }
2385
2386 /**
2387 * Return serial number stored in user directory inode.
2388 *
2389 * @return parsed serial number, or -1 if not set
2390 */
2391 private static int getSerialNumber(File file) throws IOException {
2392 try {
2393 final byte[] buf = new byte[256];
2394 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2395 final String serial = new String(buf, 0, len);
2396 try {
2397 return Integer.parseInt(serial);
2398 } catch (NumberFormatException e) {
2399 throw new IOException("Bad serial number: " + serial);
2400 }
2401 } catch (ErrnoException e) {
2402 if (e.errno == OsConstants.ENODATA) {
2403 return -1;
2404 } else {
2405 throw e.rethrowAsIOException();
2406 }
2407 }
2408 }
2409
Amith Yamasani920ace02012-09-20 22:15:37 -07002410 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002411 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2412 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2413 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2414 }
2415
2416 int onShellCommand(Shell shell, String cmd) {
2417 if (cmd == null) {
2418 return shell.handleDefaultCommands(cmd);
2419 }
2420
2421 final PrintWriter pw = shell.getOutPrintWriter();
2422 try {
2423 switch(cmd) {
2424 case "list":
2425 return runList(pw);
2426 }
2427 } catch (RemoteException e) {
2428 pw.println("Remote exception: " + e);
2429 }
2430 return -1;
2431 }
2432
2433 private int runList(PrintWriter pw) throws RemoteException {
2434 final IActivityManager am = ActivityManagerNative.getDefault();
2435 final List<UserInfo> users = getUsers(false);
2436 if (users == null) {
2437 pw.println("Error: couldn't get users");
2438 return 1;
2439 } else {
2440 pw.println("Users:");
2441 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002442 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002443 pw.println("\t" + users.get(i).toString() + running);
2444 }
2445 return 0;
2446 }
2447 }
2448
2449 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002450 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2451 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2452 != PackageManager.PERMISSION_GRANTED) {
2453 pw.println("Permission Denial: can't dump UserManager from from pid="
2454 + Binder.getCallingPid()
2455 + ", uid=" + Binder.getCallingUid()
2456 + " without permission "
2457 + android.Manifest.permission.DUMP);
2458 return;
2459 }
2460
2461 long now = System.currentTimeMillis();
2462 StringBuilder sb = new StringBuilder();
2463 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002464 synchronized (mUsersLock) {
2465 pw.println("Users:");
2466 for (int i = 0; i < mUsers.size(); i++) {
2467 UserInfo user = mUsers.valueAt(i);
2468 if (user == null) {
2469 continue;
2470 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002471 final int userId = user.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002472 pw.print(" "); pw.print(user);
2473 pw.print(" serialNo="); pw.print(user.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002474 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002475 pw.print(" <removing> ");
2476 }
2477 if (user.partial) {
2478 pw.print(" <partial>");
2479 }
2480 pw.println();
2481 pw.print(" Created: ");
2482 if (user.creationTime == 0) {
2483 pw.println("<unknown>");
2484 } else {
2485 sb.setLength(0);
2486 TimeUtils.formatDuration(now - user.creationTime, sb);
2487 sb.append(" ago");
2488 pw.println(sb);
2489 }
2490 pw.print(" Last logged in: ");
2491 if (user.lastLoggedInTime == 0) {
2492 pw.println("<unknown>");
2493 } else {
2494 sb.setLength(0);
2495 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2496 sb.append(" ago");
2497 pw.println(sb);
2498 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002499 pw.print(" Has profile owner: ");
2500 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002501 pw.println(" Restrictions:");
2502 synchronized (mRestrictionsLock) {
2503 UserRestrictionsUtils.dumpRestrictions(
2504 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002505 pw.println(" Device policy local restrictions:");
2506 UserRestrictionsUtils.dumpRestrictions(
2507 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002508 pw.println(" Effective restrictions:");
2509 UserRestrictionsUtils.dumpRestrictions(
2510 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2511 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002512 pw.println();
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002513 String accountName = mUserAccounts.get(userId);
2514 if (accountName != null) {
2515 pw.print(" Account name: " + accountName);
2516 pw.println();
2517 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002518 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002519 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002520 pw.println(" Device policy global restrictions:");
2521 synchronized (mRestrictionsLock) {
2522 UserRestrictionsUtils
2523 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2524 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002525 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002526 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002527 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002528 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002529 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002530 synchronized (mUsersLock) {
2531 pw.println();
2532 pw.println(" Device managed: " + mIsDeviceManaged);
2533 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002534 }
2535 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002536
2537 final class MainHandler extends Handler {
2538
2539 @Override
2540 public void handleMessage(Message msg) {
2541 switch (msg.what) {
2542 case WRITE_USER_MSG:
2543 removeMessages(WRITE_USER_MSG, msg.obj);
2544 synchronized (mPackagesLock) {
2545 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002546 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002547 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002548 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002549 }
2550 }
2551 }
2552 }
2553 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002554
2555 /**
2556 * @param userId
2557 * @return whether the user has been initialized yet
2558 */
2559 boolean isInitialized(int userId) {
2560 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2561 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002562
2563 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002564 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002565 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2566 @Nullable Bundle globalRestrictions) {
2567 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2568 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002569 }
2570
2571 @Override
2572 public Bundle getBaseUserRestrictions(int userId) {
2573 synchronized (mRestrictionsLock) {
2574 return mBaseUserRestrictions.get(userId);
2575 }
2576 }
2577
2578 @Override
2579 public void setBaseUserRestrictionsByDpmsForMigration(
2580 int userId, Bundle baseRestrictions) {
2581 synchronized (mRestrictionsLock) {
2582 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002583 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002584 }
2585
Fyodor Kupolov82402752015-10-28 14:54:51 -07002586 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002587 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002588 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002589 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002590 } else {
2591 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2592 }
2593 }
2594 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002595
2596 @Override
2597 public boolean getUserRestriction(int userId, String key) {
2598 return getUserRestrictions(userId).getBoolean(key);
2599 }
2600
2601 @Override
2602 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2603 synchronized (mUserRestrictionsListeners) {
2604 mUserRestrictionsListeners.add(listener);
2605 }
2606 }
2607
2608 @Override
2609 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2610 synchronized (mUserRestrictionsListeners) {
2611 mUserRestrictionsListeners.remove(listener);
2612 }
2613 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002614
2615 @Override
2616 public void setDeviceManaged(boolean isManaged) {
2617 synchronized (mUsersLock) {
2618 mIsDeviceManaged = isManaged;
2619 }
2620 }
2621
2622 @Override
2623 public void setUserManaged(int userId, boolean isManaged) {
2624 synchronized (mUsersLock) {
2625 mIsUserManaged.put(userId, isManaged);
2626 }
2627 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002628 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002629
2630 private class Shell extends ShellCommand {
2631 @Override
2632 public int onCommand(String cmd) {
2633 return onShellCommand(this, cmd);
2634 }
2635
2636 @Override
2637 public void onHelp() {
2638 final PrintWriter pw = getOutPrintWriter();
2639 pw.println("User manager (user) commands:");
2640 pw.println(" help");
2641 pw.println(" Print this help text.");
2642 pw.println("");
2643 pw.println(" list");
2644 pw.println(" Prints all users on the system.");
2645 }
2646 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002647
2648 private static void debug(String message) {
2649 Log.d(LOG_TAG, message +
2650 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2651 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002652}