blob: 5100faf258b4a22a84f05b035d703669690e283b [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;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080072import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080073import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070074import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070075import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000076import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070077import com.android.server.LocalServices;
Jeff Sharkey0e62384c2016-01-13 18:52:55 -070078import com.android.server.pm.Installer.StorageFlags;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080079
80import org.xmlpull.v1.XmlPullParser;
81import org.xmlpull.v1.XmlPullParserException;
82import org.xmlpull.v1.XmlSerializer;
83
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084import java.io.BufferedOutputStream;
85import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070086import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070088import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070089import java.io.FileOutputStream;
90import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070091import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010092import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093import java.util.ArrayList;
94import java.util.List;
95
Fyodor Kupolov262f9952015-03-23 18:55:11 -070096import libcore.io.IoUtils;
Xiaohui Chenb3b92582015-12-07 11:22:13 -080097import libcore.util.Objects;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070098
Makoto Onuki068c54a2015-10-13 14:34:03 -070099/**
100 * Service for {@link UserManager}.
101 *
102 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700103 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800104 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700105 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
106 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
107 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700108 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700109public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700110 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800111 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
112 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700113
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800115 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700117 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700119 private static final String ATTR_CREATION_TIME = "created";
120 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700121 private static final String ATTR_SERIAL_NO = "serialNumber";
122 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700123 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700124 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700125 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100126 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700127 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530128 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700129 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700130 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800131 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800132 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800133 private static final String TAG_ENTRY = "entry";
134 private static final String TAG_VALUE = "value";
135 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700136 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800137 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700139 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
140 private static final String ATTR_TYPE_STRING = "s";
141 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700142 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700143 private static final String ATTR_TYPE_BUNDLE = "B";
144 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700145
Amith Yamasani0b285492011-04-14 17:35:23 -0700146 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700148 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100149 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700150
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800151 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700152 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800153
Amith Yamasani634cf312012-10-04 17:34:21 -0700154 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700155 // We need to keep process uid within Integer.MAX_VALUE.
156 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700157
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700158 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700159
Amith Yamasani920ace02012-09-20 22:15:37 -0700160 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
161
Nicolas Prevotb8186812015-08-06 15:00:03 +0100162 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700163 // without first making sure that the rest of the framework is prepared for it.
164 private static final int MAX_MANAGED_PROFILES = 1;
165
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800166 static final int WRITE_USER_MSG = 1;
167 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530168
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700169 private static final String XATTR_SERIAL = "user.serial";
170
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800171 // Tron counters
172 private static final String TRON_GUEST_CREATED = "users_guest_created";
173 private static final String TRON_USER_CREATED = "users_user_created";
174
Dianne Hackborn4428e172012-08-24 17:43:05 -0700175 private final Context mContext;
176 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700177 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700178 // Short-term lock for internal state, when interaction/sync with PM is not required
179 private final Object mUsersLock = new Object();
180 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700181
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800182 private final Handler mHandler;
183
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700184 private final File mUsersDir;
185 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700186
Fyodor Kupolov82402752015-10-28 14:54:51 -0700187 @GuardedBy("mUsersLock")
188 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700189
190 /**
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800191 * This collection contains each user's account name if the user chose to set one up
192 * during the initial user creation process. Keeping this information separate from mUsers
193 * to avoid accidentally leak it.
194 */
195 @GuardedBy("mUsersLock")
196 private final SparseArray<String> mUserAccounts = new SparseArray<>();
197
198 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700199 * User restrictions set via UserManager. This doesn't include restrictions set by
200 * device owner / profile owners.
201 *
202 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
203 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
204 * maybe shared between {@link #mBaseUserRestrictions} and
205 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
206 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700207 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700208 */
209 @GuardedBy("mRestrictionsLock")
210 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
211
212 /**
213 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
214 * with device / profile owner restrictions. We'll initialize it lazily; use
215 * {@link #getEffectiveUserRestrictions} to access it.
216 *
217 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
218 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
219 * maybe shared between {@link #mBaseUserRestrictions} and
220 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
221 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700222 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700223 */
224 @GuardedBy("mRestrictionsLock")
225 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
226
Makoto Onuki4f160732015-10-27 17:15:38 -0700227 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800228 * User restrictions that have already been applied in
229 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
230 * that have changed since the last
231 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700232 */
233 @GuardedBy("mRestrictionsLock")
234 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
235
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800236 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800237 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
238 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800239 */
240 @GuardedBy("mRestrictionsLock")
241 private Bundle mDevicePolicyGlobalUserRestrictions;
242
243 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800244 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
245 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800246 */
247 @GuardedBy("mRestrictionsLock")
248 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
249
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800250 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530251 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800252
253 /**
254 * Set of user IDs being actively removed. Removed IDs linger in this set
255 * for several seconds to work around a VFS caching issue.
256 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700257 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800258 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700259
Fyodor Kupolov82402752015-10-28 14:54:51 -0700260 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700261 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800262 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700263 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700264 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700265
Jason Monk62062992014-05-06 09:55:28 -0400266 private IAppOpsService mAppOpsService;
267
Makoto Onuki068c54a2015-10-13 14:34:03 -0700268 private final LocalService mLocalService;
269
Makoto Onukie7927da2015-11-25 10:05:17 -0800270 @GuardedBy("mUsersLock")
271 private boolean mIsDeviceManaged;
272
273 @GuardedBy("mUsersLock")
274 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
275
Makoto Onukid45a4a22015-11-02 17:17:38 -0800276 @GuardedBy("mUserRestrictionsListeners")
277 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
278 new ArrayList<>();
279
Clara Bayarria1771112015-12-18 16:29:18 +0000280 private final LockPatternUtils mLockPatternUtils;
281
Amith Yamasani258848d2012-08-10 17:06:33 -0700282 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700283
Dianne Hackborn4428e172012-08-24 17:43:05 -0700284 public static UserManagerService getInstance() {
285 synchronized (UserManagerService.class) {
286 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700287 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700288 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700289
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800290 @VisibleForTesting
291 UserManagerService(File dataDir) {
292 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700293 }
294
Dianne Hackborn4428e172012-08-24 17:43:05 -0700295 /**
296 * Called by package manager to create the service. This is closely
297 * associated with the package manager, and the given lock is the
298 * package manager's own lock.
299 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800300 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
301 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700302 }
303
Dianne Hackborn4428e172012-08-24 17:43:05 -0700304 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800305 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700306 mContext = context;
307 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700308 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800309 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800310 synchronized (mPackagesLock) {
311 mUsersDir = new File(dataDir, USER_INFO_DIR);
312 mUsersDir.mkdirs();
313 // Make zeroth user directory, for services to migrate their files to that location
314 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
315 userZeroDir.mkdirs();
316 FileUtils.setPermissions(mUsersDir.toString(),
317 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
318 -1, -1);
319 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
320 initDefaultGuestRestrictions();
321 readUserListLP();
322 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700323 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700324 mLocalService = new LocalService();
325 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000326 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700327 }
328
329 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100330 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800331 ArrayList<UserInfo> partials = new ArrayList<>();
332 synchronized (mUsersLock) {
333 final int userSize = mUsers.size();
334 for (int i = 0; i < userSize; i++) {
335 UserInfo ui = mUsers.valueAt(i);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100336 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800337 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700338 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700339 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700340 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800341 final int partialsSize = partials.size();
342 for (int i = 0; i < partialsSize; i++) {
343 UserInfo ui = partials.get(i);
344 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
345 + " (name=" + ui.name + ")");
346 removeUserState(ui.id);
347 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800348
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700349 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800350
Jason Monk62062992014-05-06 09:55:28 -0400351 mAppOpsService = IAppOpsService.Stub.asInterface(
352 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800353
354 synchronized (mRestrictionsLock) {
355 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400356 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700357 }
358
359 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800360 public String getUserAccount(int userId) {
361 checkManageUserAndAcrossUsersFullPermission("get user account");
362 synchronized (mUsersLock) {
363 return mUserAccounts.get(userId);
364 }
365 }
366
367 @Override
368 public void setUserAccount(int userId, String accountName) {
369 checkManageUserAndAcrossUsersFullPermission("set user account");
370 UserInfo userToUpdate = null;
371 synchronized (mPackagesLock) {
372 synchronized (mUsersLock) {
373 String currentAccount = mUserAccounts.get(userId);
374 if (!Objects.equal(currentAccount, accountName)) {
375 mUserAccounts.put(userId, accountName);
376 userToUpdate = mUsers.get(userId);
377 }
378 }
379
380 if (userToUpdate != null) {
381 writeUserLP(userToUpdate);
382 }
383 }
384 }
385
386 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700387 public UserInfo getPrimaryUser() {
388 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700389 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700390 final int userSize = mUsers.size();
391 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700392 UserInfo ui = mUsers.valueAt(i);
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800393 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700394 return ui;
395 }
396 }
397 }
398 return null;
399 }
400
401 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700402 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700403 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700404 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700405 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700406 final int userSize = mUsers.size();
407 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700408 UserInfo ui = mUsers.valueAt(i);
409 if (ui.partial) {
410 continue;
411 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800412 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700413 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700414 }
Amith Yamasani13593602012-03-22 16:16:17 -0700415 }
416 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700417 }
Amith Yamasani13593602012-03-22 16:16:17 -0700418 }
419
Amith Yamasani258848d2012-08-10 17:06:33 -0700420 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100421 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800422 if (userId != UserHandle.getCallingUserId()) {
423 checkManageUsersPermission("getting profiles related to user " + userId);
424 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700425 final long ident = Binder.clearCallingIdentity();
426 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700427 synchronized (mUsersLock) {
428 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100429 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700430 } finally {
431 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000432 }
433 }
434
Amith Yamasanibe465322014-04-24 13:45:17 -0700435 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700436 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
437 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700438 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700439 if (user == null) {
440 // Probably a dying user
441 return users;
442 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700443 final int userSize = mUsers.size();
444 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700445 UserInfo profile = mUsers.valueAt(i);
446 if (!isProfileOf(user, profile)) {
447 continue;
448 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100449 if (enabledOnly && !profile.isEnabled()) {
450 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700451 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700452 if (mRemovingUserIds.get(profile.id)) {
453 continue;
454 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700455 users.add(profile);
456 }
457 return users;
458 }
459
Jessica Hummelbe81c802014-04-22 15:49:22 +0100460 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700461 public int getCredentialOwnerProfile(int userHandle) {
462 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000463 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700464 synchronized (mUsersLock) {
465 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700466 if (profileParent != null) {
467 return profileParent.id;
468 }
469 }
470 }
471
472 return userHandle;
473 }
474
475 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700476 public boolean isSameProfileGroup(int userId, int otherUserId) {
477 if (userId == otherUserId) return true;
478 checkManageUsersPermission("check if in the same profile group");
479 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700480 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700481 }
482 }
483
Fyodor Kupolov82402752015-10-28 14:54:51 -0700484 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
485 synchronized (mUsersLock) {
486 UserInfo userInfo = getUserInfoLU(userId);
487 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
488 return false;
489 }
490 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
491 if (otherUserInfo == null
492 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
493 return false;
494 }
495 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700496 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700497 }
498
499 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100500 public UserInfo getProfileParent(int userHandle) {
501 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700502 synchronized (mUsersLock) {
503 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700504 }
505 }
506
Fyodor Kupolov82402752015-10-28 14:54:51 -0700507 private UserInfo getProfileParentLU(int userHandle) {
508 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700509 if (profile == null) {
510 return null;
511 }
512 int parentUserId = profile.profileGroupId;
513 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
514 return null;
515 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700516 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100517 }
518 }
519
Fyodor Kupolov82402752015-10-28 14:54:51 -0700520 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100521 return user.id == profile.id ||
522 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
523 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000524 }
525
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000526 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
527 UserHandle parentHandle, Bundle extras) {
528 // Send intent to profile
529 Intent intent = new Intent(Intent.ACTION_AVAILABILITY_CHANGED);
530 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
531 intent.putExtras(extras);
532 mContext.sendBroadcastAsUser(intent, profileHandle);
533
534 // Send intent to parent
535 if (parentHandle != null) {
536 intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
537 intent.putExtra(Intent.EXTRA_USER, profileHandle);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700538 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000539 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
540 intent.putExtras(extras);
541 mContext.sendBroadcastAsUser(intent, parentHandle);
542 }
543 }
544
545 @Override
546 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
547 checkManageUsersPermission("silence profile");
548 boolean changed = false;
549 UserInfo profile, parent;
550 synchronized (mPackagesLock) {
551 synchronized (mUsersLock) {
552 profile = getUserInfoLU(userHandle);
553 parent = getProfileParentLU(userHandle);
554
555 }
556 if (profile == null || !profile.isManagedProfile()) {
557 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
558 }
559 if (profile.isQuietModeEnabled() != enableQuietMode) {
560 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
561 writeUserLP(profile);
562 changed = true;
563 }
564 }
565 if (changed) {
566 Bundle extras = new Bundle();
567 extras.putBoolean(Intent.EXTRA_QUIET_MODE, enableQuietMode);
568 broadcastProfileAvailabilityChanges(profile.getUserHandle(),
569 parent != null ? parent.getUserHandle() : null, extras);
570 }
571 }
572
573 @Override
574 public boolean isQuietModeEnabled(int userHandle) {
575 synchronized (mPackagesLock) {
576 UserInfo info;
577 synchronized (mUsersLock) {
578 info = getUserInfoLU(userHandle);
579 }
580 if (info == null || !info.isManagedProfile()) {
581 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
582 }
583 return info.isQuietModeEnabled();
584 }
585 }
586
Kenny Guya52dc3e2014-02-11 15:33:14 +0000587 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100588 public void setUserEnabled(int userId) {
589 checkManageUsersPermission("enable user");
590 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700591 UserInfo info;
592 synchronized (mUsersLock) {
593 info = getUserInfoLU(userId);
594 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100595 if (info != null && !info.isEnabled()) {
596 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700597 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100598 }
599 }
600 }
601
602 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700603 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700604 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700605 synchronized (mUsersLock) {
606 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700607 }
608 }
609
Amith Yamasani71e6c692013-03-24 17:39:28 -0700610 @Override
611 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700612 synchronized (mUsersLock) {
613 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700614 }
615 }
616
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700617 @Override
618 public boolean canHaveRestrictedProfile(int userId) {
619 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700620 synchronized (mUsersLock) {
621 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700622 if (userInfo == null || !userInfo.canHaveProfile()) {
623 return false;
624 }
625 if (!userInfo.isAdmin()) {
626 return false;
627 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800628 // restricted profile can be created if there is no DO set and the admin user has no PO;
629 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700630 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700631 }
632
Amith Yamasani195263742012-08-21 15:40:12 -0700633 /*
634 * Should be locked on mUsers before calling this.
635 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700636 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700637 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700638 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800639 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700640 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
641 return null;
642 }
643 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700644 }
645
Fyodor Kupolov82402752015-10-28 14:54:51 -0700646 /**
647 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
648 * <p>No permissions checking or any addition checks are made</p>
649 */
650 private UserInfo getUserInfoNoChecks(int userId) {
651 synchronized (mUsersLock) {
652 return mUsers.get(userId);
653 }
654 }
655
Amith Yamasani236b2b52015-08-18 14:32:14 -0700656 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700657 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700658 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700659 }
660
Amith Yamasani258848d2012-08-10 17:06:33 -0700661 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700662 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700663 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700664 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700665 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700666 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700667 if (info == null || info.partial) {
668 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
669 return;
670 }
Amith Yamasani13593602012-03-22 16:16:17 -0700671 if (name != null && !name.equals(info.name)) {
672 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700673 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700674 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700675 }
676 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700677 if (changed) {
678 sendUserInfoChangedBroadcast(userId);
679 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700680 }
681
Amith Yamasani258848d2012-08-10 17:06:33 -0700682 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700683 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700684 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400685 long ident = Binder.clearCallingIdentity();
686 try {
687 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700688 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400689 if (info == null || info.partial) {
690 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
691 return;
692 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700693 writeBitmapLP(info, bitmap);
694 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700695 }
Jason Monk9a944532014-07-08 09:31:21 -0400696 sendUserInfoChangedBroadcast(userId);
697 } finally {
698 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700699 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700700 }
701
702 private void sendUserInfoChangedBroadcast(int userId) {
703 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
704 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
705 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700706 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700707 }
708
Amith Yamasani258848d2012-08-10 17:06:33 -0700709 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100710 public ParcelFileDescriptor getUserIcon(int userId) {
711 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700712 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700713 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700714 if (info == null || info.partial) {
715 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
716 return null;
717 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700718 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100719 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
720 || callingGroupId != info.profileGroupId) {
721 checkManageUsersPermission("get the icon of a user who is not related");
722 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700723 if (info.iconPath == null) {
724 return null;
725 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100726 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700727 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100728
729 try {
730 return ParcelFileDescriptor.open(
731 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
732 } catch (FileNotFoundException e) {
733 Log.e(LOG_TAG, "Couldn't find icon file", e);
734 }
735 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700736 }
737
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700738 public void makeInitialized(int userId) {
739 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800740 boolean scheduleWriteUser = false;
741 UserInfo info;
742 synchronized (mUsersLock) {
743 info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700744 if (info == null || info.partial) {
745 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800746 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700747 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800748 if ((info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700749 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800750 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700751 }
752 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800753 if (scheduleWriteUser) {
754 scheduleWriteUser(info);
755 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700756 }
757
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700758 /**
759 * If default guest restrictions haven't been initialized yet, add the basic
760 * restrictions.
761 */
762 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800763 synchronized (mGuestRestrictions) {
764 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800765 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800766 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
767 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
768 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700769 }
770 }
771
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800772 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530773 public Bundle getDefaultGuestRestrictions() {
774 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800775 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530776 return new Bundle(mGuestRestrictions);
777 }
778 }
779
780 @Override
781 public void setDefaultGuestRestrictions(Bundle restrictions) {
782 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800783 synchronized (mGuestRestrictions) {
784 mGuestRestrictions.clear();
785 mGuestRestrictions.putAll(restrictions);
786 }
787 synchronized (mPackagesLock) {
788 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530789 }
790 }
791
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800792 /**
793 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
794 */
795 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
796 @Nullable Bundle global) {
797 Preconditions.checkNotNull(local);
798 boolean globalChanged = false;
799 boolean localChanged;
800 synchronized (mRestrictionsLock) {
801 if (global != null) {
802 // Update global.
803 globalChanged = !UserRestrictionsUtils.areEqual(
804 mDevicePolicyGlobalUserRestrictions, global);
805 if (globalChanged) {
806 mDevicePolicyGlobalUserRestrictions = global;
807 }
808 }
809 {
810 // Update local.
811 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
812 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
813 if (localChanged) {
814 mDevicePolicyLocalUserRestrictions.put(userId, local);
815 }
816 }
817 }
818 if (DBG) {
819 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
820 + " global=" + global + (globalChanged ? " (changed)" : "")
821 + " local=" + local + (localChanged ? " (changed)" : "")
822 );
823 }
824 // Don't call them within the mRestrictionsLock.
825 synchronized (mPackagesLock) {
826 if (globalChanged) {
827 writeUserListLP();
828 }
829 if (localChanged) {
830 writeUserLP(getUserInfoNoChecks(userId));
831 }
832 }
833
834 synchronized (mRestrictionsLock) {
835 if (globalChanged) {
836 applyUserRestrictionsForAllUsersLR();
837 } else if (localChanged) {
838 applyUserRestrictionsLR(userId);
839 }
840 }
841 }
842
Makoto Onuki068c54a2015-10-13 14:34:03 -0700843 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700844 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800845 final Bundle baseRestrictions =
846 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
847 final Bundle global = mDevicePolicyGlobalUserRestrictions;
848 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700849
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800850 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
851 // Common case first.
852 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700853 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800854 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
855 UserRestrictionsUtils.merge(effective, global);
856 UserRestrictionsUtils.merge(effective, local);
857
Makoto Onuki068c54a2015-10-13 14:34:03 -0700858 return effective;
859 }
860
861 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700862 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700863 if (DBG) {
864 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
865 }
866 mCachedEffectiveUserRestrictions.remove(userId);
867 }
868
869 private Bundle getEffectiveUserRestrictions(int userId) {
870 synchronized (mRestrictionsLock) {
871 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
872 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700873 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700874 mCachedEffectiveUserRestrictions.put(userId, restrictions);
875 }
876 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700877 }
878 }
879
Makoto Onuki068c54a2015-10-13 14:34:03 -0700880 /** @return a specific user restriction that's in effect currently. */
881 @Override
882 public boolean hasUserRestriction(String restrictionKey, int userId) {
883 Bundle restrictions = getEffectiveUserRestrictions(userId);
884 return restrictions != null && restrictions.getBoolean(restrictionKey);
885 }
886
887 /**
888 * @return UserRestrictions that are in effect currently. This always returns a new
889 * {@link Bundle}.
890 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700891 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800892 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800893 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800894 }
895
896 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000897 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
898 checkManageUsersPermission("hasBaseUserRestriction");
899 synchronized (mRestrictionsLock) {
900 Bundle bundle = mBaseUserRestrictions.get(userId);
901 return (bundle != null && bundle.getBoolean(restrictionKey, false));
902 }
903 }
904
905 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700906 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700907 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700908 synchronized (mRestrictionsLock) {
909 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
910 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800911 final Bundle newRestrictions = UserRestrictionsUtils.clone(
912 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700913 newRestrictions.putBoolean(key, value);
914
Fyodor Kupolov82402752015-10-28 14:54:51 -0700915 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700916 }
917 }
918
Makoto Onuki068c54a2015-10-13 14:34:03 -0700919 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800920 * Optionally updating user restrictions, calculate the effective user restrictions and also
921 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700922 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800923 * @param newRestrictions User restrictions to set.
924 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700925 * @param userId target user ID.
926 */
927 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700928 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700929 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800930
931 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
932 mAppliedUserRestrictions.get(userId));
933
934 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700935 if (newRestrictions != null) {
936 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800937 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
938
939 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700940 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
941 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800942
943 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
944 mBaseUserRestrictions.put(userId, newRestrictions);
945 scheduleWriteUser(getUserInfoNoChecks(userId));
946 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700947 }
948
Fyodor Kupolov82402752015-10-28 14:54:51 -0700949 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700950
Makoto Onuki759a7632015-10-28 16:43:10 -0700951 mCachedEffectiveUserRestrictions.put(userId, effective);
952
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800953 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700954 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800955 debug("Applying user restrictions: userId=" + userId
956 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700957 }
958
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800959 if (mAppOpsService != null) { // We skip it until system-ready.
960 final long token = Binder.clearCallingIdentity();
961 try {
962 mAppOpsService.setUserRestrictions(effective, userId);
963 } catch (RemoteException e) {
964 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
965 } finally {
966 Binder.restoreCallingIdentity(token);
967 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700968 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700969
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800970 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700971
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800972 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700973 }
974
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800975 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800976 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800977 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
978 // actually, but we still need some kind of synchronization otherwise we might end up
979 // calling listeners out-of-order, thus "LR".
980
981 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
982 return;
983 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800984
985 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
986 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
987
988 mHandler.post(new Runnable() {
989 @Override
990 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700991 UserRestrictionsUtils.applyUserRestrictions(
992 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800993
Makoto Onukid45a4a22015-11-02 17:17:38 -0800994 final UserRestrictionsListener[] listeners;
995 synchronized (mUserRestrictionsListeners) {
996 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
997 mUserRestrictionsListeners.toArray(listeners);
998 }
999 for (int i = 0; i < listeners.length; i++) {
1000 listeners[i].onUserRestrictionsChanged(userId,
1001 newRestrictionsFinal, prevRestrictionsFinal);
1002 }
1003 }
1004 });
1005 }
1006
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001007 // Package private for the inner class.
1008 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001009 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001010 }
1011
1012 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001013 // Package private for the inner class.
1014 void applyUserRestrictionsForAllUsersLR() {
1015 if (DBG) {
1016 debug("applyUserRestrictionsForAllUsersLR");
1017 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001018 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001019 mCachedEffectiveUserRestrictions.clear();
1020
Makoto Onuki068c54a2015-10-13 14:34:03 -07001021 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1022 // it on a handler.
1023 final Runnable r = new Runnable() {
1024 @Override
1025 public void run() {
1026 // Then get the list of running users.
1027 final int[] runningUsers;
1028 try {
1029 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1030 } catch (RemoteException e) {
1031 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1032 return;
1033 }
1034 // Then re-calculate the effective restrictions and apply, only for running users.
1035 // It's okay if a new user has started after the getRunningUserIds() call,
1036 // because we'll do the same thing (re-calculate the restrictions and apply)
1037 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001038 synchronized (mRestrictionsLock) {
1039 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001040 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001041 }
1042 }
1043 }
1044 };
1045 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001046 }
1047
Amith Yamasani258848d2012-08-10 17:06:33 -07001048 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001049 * Check if we've hit the limit of how many users can be created.
1050 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001051 private boolean isUserLimitReached() {
1052 int count;
1053 synchronized (mUsersLock) {
1054 count = getAliveUsersExcludingGuestsCountLU();
1055 }
1056 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001057 }
1058
1059 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001060 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001061 checkManageUsersPermission("check if more managed profiles can be added.");
1062 if (ActivityManager.isLowRamDeviceStatic()) {
1063 return false;
1064 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001065 if (!mContext.getPackageManager().hasSystemFeature(
1066 PackageManager.FEATURE_MANAGED_USERS)) {
1067 return false;
1068 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001069 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001070 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1071 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1072 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001073 return false;
1074 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001075 synchronized(mUsersLock) {
1076 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001077 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001078 return false;
1079 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001080 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1081 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001082 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001083 return usersCountAfterRemoving == 1
1084 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001085 }
1086 }
1087
Fyodor Kupolov82402752015-10-28 14:54:51 -07001088 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001089 int aliveUserCount = 0;
1090 final int totalUserCount = mUsers.size();
1091 // Skip over users being removed
1092 for (int i = 0; i < totalUserCount; i++) {
1093 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001094 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001095 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001096 aliveUserCount++;
1097 }
1098 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001099 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001100 }
1101
1102 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001103 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001104 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1105 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1106 * permissions can make certain calls to the UserManager.
1107 *
1108 * @param message used as message if SecurityException is thrown
1109 * @throws SecurityException if the caller does not have enough privilege.
1110 */
1111 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1112 final int uid = Binder.getCallingUid();
1113 if (uid != Process.SYSTEM_UID && uid != 0
1114 && ActivityManager.checkComponentPermission(
1115 Manifest.permission.MANAGE_USERS,
1116 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1117 && ActivityManager.checkComponentPermission(
1118 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1119 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1120 throw new SecurityException(
1121 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1122 + message);
1123 }
1124 }
1125
1126 /**
1127 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001128 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001129 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001130 *
1131 * @param message used as message if SecurityException is thrown
1132 * @throws SecurityException if the caller is not system or root
1133 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001134 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001135 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001136 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001137 && ActivityManager.checkComponentPermission(
1138 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001139 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1140 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1141 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001142 }
1143
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001144 /**
1145 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1146 * UserManager.
1147 *
1148 * @param message used as message if SecurityException is thrown
1149 * @throws SecurityException if the caller is not system or root
1150 */
1151 private static void checkSystemOrRoot(String message) {
1152 final int uid = Binder.getCallingUid();
1153 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1154 throw new SecurityException("Only system may: " + message);
1155 }
1156 }
1157
Fyodor Kupolov82402752015-10-28 14:54:51 -07001158 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001159 try {
1160 File dir = new File(mUsersDir, Integer.toString(info.id));
1161 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001162 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001163 if (!dir.exists()) {
1164 dir.mkdir();
1165 FileUtils.setPermissions(
1166 dir.getPath(),
1167 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1168 -1, -1);
1169 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001170 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001171 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1172 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001173 info.iconPath = file.getAbsolutePath();
1174 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001175 try {
1176 os.close();
1177 } catch (IOException ioe) {
1178 // What the ... !
1179 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001180 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001181 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001182 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001183 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001184 }
1185
Amith Yamasani0b285492011-04-14 17:35:23 -07001186 /**
1187 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1188 * cache it elsewhere.
1189 * @return the array of user ids.
1190 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001191 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001192 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001193 return mUserIds;
1194 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001195 }
1196
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001197 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001198 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001199 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001200 return;
1201 }
1202 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001203 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001204 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001205 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001206 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001207 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001208 int type;
1209 while ((type = parser.next()) != XmlPullParser.START_TAG
1210 && type != XmlPullParser.END_DOCUMENT) {
1211 ;
1212 }
1213
1214 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001215 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001216 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001217 return;
1218 }
1219
Amith Yamasani2a003292012-08-14 18:25:45 -07001220 mNextSerialNumber = -1;
1221 if (parser.getName().equals(TAG_USERS)) {
1222 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1223 if (lastSerialNumber != null) {
1224 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1225 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001226 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1227 if (versionNumber != null) {
1228 mUserVersion = Integer.parseInt(versionNumber);
1229 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001230 }
1231
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001232 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1233
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001234 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301235 if (type == XmlPullParser.START_TAG) {
1236 final String name = parser.getName();
1237 if (name.equals(TAG_USER)) {
1238 String id = parser.getAttributeValue(null, ATTR_ID);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001239 Pair<UserInfo, String> userPair = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001240
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001241 if (userPair != null) {
1242 UserInfo user = userPair.first;
1243 String account = userPair.second;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001244 synchronized (mUsersLock) {
1245 mUsers.put(user.id, user);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001246 mUserAccounts.put(user.id, account);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001247 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1248 mNextSerialNumber = user.id + 1;
1249 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301250 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001251 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301252 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001253 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1254 && type != XmlPullParser.END_TAG) {
1255 if (type == XmlPullParser.START_TAG) {
1256 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001257 synchronized (mGuestRestrictions) {
1258 UserRestrictionsUtils
1259 .readRestrictions(parser, mGuestRestrictions);
1260 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001261 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1262 ) {
1263 UserRestrictionsUtils.readRestrictions(parser,
1264 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001265 }
1266 break;
1267 }
1268 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001269 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001270 }
1271 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001272 synchronized (mRestrictionsLock) {
1273 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1274 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001275 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001276 upgradeIfNecessaryLP();
1277 } catch (IOException | XmlPullParserException e) {
1278 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001279 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001280 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001281 }
1282 }
1283
Amith Yamasani6f34b412012-10-22 18:19:27 -07001284 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001285 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001286 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001287 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001288 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001289 int userVersion = mUserVersion;
1290 if (userVersion < 1) {
1291 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001292 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001293 if ("Primary".equals(user.name)) {
1294 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001295 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001296 }
1297 userVersion = 1;
1298 }
1299
Amith Yamasanibc9625052012-11-15 14:39:18 -08001300 if (userVersion < 2) {
1301 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001302 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001303 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1304 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001305 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001306 }
1307 userVersion = 2;
1308 }
1309
Amith Yamasani350962c2013-08-06 11:18:53 -07001310
Amith Yamasani5e486f52013-08-07 11:06:44 -07001311 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001312 userVersion = 4;
1313 }
1314
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001315 if (userVersion < 5) {
1316 initDefaultGuestRestrictions();
1317 userVersion = 5;
1318 }
1319
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001320 if (userVersion < 6) {
1321 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001322 synchronized (mUsersLock) {
1323 for (int i = 0; i < mUsers.size(); i++) {
1324 UserInfo user = mUsers.valueAt(i);
1325 // In non-split mode, only user 0 can have restricted profiles
1326 if (!splitSystemUser && user.isRestricted()
1327 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1328 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001329 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001330 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001331 }
1332 }
1333 userVersion = 6;
1334 }
1335
Amith Yamasani6f34b412012-10-22 18:19:27 -07001336 if (userVersion < USER_VERSION) {
1337 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1338 + USER_VERSION);
1339 } else {
1340 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001341
1342 if (originalVersion < mUserVersion) {
1343 writeUserListLP();
1344 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001345 }
1346 }
1347
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001348 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001349 int flags = UserInfo.FLAG_INITIALIZED;
1350 // In split system user mode, the admin and primary flags are assigned to the first human
1351 // user.
1352 if (!UserManager.isSplitSystemUser()) {
1353 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1354 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001355 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001356 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001357 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001358 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001359 synchronized (mUsersLock) {
1360 mUsers.put(system.id, system);
1361 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001362 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001363 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001364
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001365 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001366 synchronized (mRestrictionsLock) {
1367 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1368 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001369
Fyodor Kupolov82402752015-10-28 14:54:51 -07001370 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001371 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001372
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001373 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001374 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001375 }
1376
Makoto Onuki9e935a32015-11-06 14:24:24 -08001377 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001378 if (DBG) {
1379 debug("scheduleWriteUser");
1380 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001381 // No need to wrap it within a lock -- worst case, we'll just post the same message
1382 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001383 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1384 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1385 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1386 }
1387 }
1388
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001389 /*
1390 * Writes the user file in this format:
1391 *
1392 * <user flags="20039023" id="0">
1393 * <name>Primary</name>
1394 * </user>
1395 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001396 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001397 if (DBG) {
1398 debug("writeUserLP " + userInfo);
1399 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001400 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001401 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001402 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001403 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001404 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1405
1406 // XmlSerializer serializer = XmlUtils.serializerInstance();
1407 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001408 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001409 serializer.startDocument(null, true);
1410 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1411
1412 serializer.startTag(null, TAG_USER);
1413 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001414 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001415 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001416 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1417 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1418 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001419 if (userInfo.iconPath != null) {
1420 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1421 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001422 if (userInfo.partial) {
1423 serializer.attribute(null, ATTR_PARTIAL, "true");
1424 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001425 if (userInfo.guestToRemove) {
1426 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1427 }
Kenny Guy2a764942014-04-02 13:29:20 +01001428 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1429 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1430 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001431 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001432 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1433 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1434 Integer.toString(userInfo.restrictedProfileParentId));
1435 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001436 serializer.startTag(null, TAG_NAME);
1437 serializer.text(userInfo.name);
1438 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001439 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001440 UserRestrictionsUtils.writeRestrictions(serializer,
1441 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1442 UserRestrictionsUtils.writeRestrictions(serializer,
1443 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1444 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001445 }
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001446 // Update the account field if it is set.
1447 String account;
1448 synchronized (mUsersLock) {
1449 account = mUserAccounts.get(userInfo.id);
1450 }
1451 if (account != null) {
1452 serializer.startTag(null, TAG_ACCOUNT);
1453 serializer.text(account);
1454 serializer.endTag(null, TAG_ACCOUNT);
1455 }
1456
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001457 serializer.endTag(null, TAG_USER);
1458
1459 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001460 userFile.finishWrite(fos);
1461 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001462 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001463 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001464 }
1465 }
1466
1467 /*
1468 * Writes the user list file in this format:
1469 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001470 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001471 * <user id="0"></user>
1472 * <user id="2"></user>
1473 * </users>
1474 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001475 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001476 if (DBG) {
1477 debug("writeUserList");
1478 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001479 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001480 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001481 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001482 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001483 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1484
1485 // XmlSerializer serializer = XmlUtils.serializerInstance();
1486 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001487 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001488 serializer.startDocument(null, true);
1489 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1490
1491 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001492 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001493 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001494
Adam Lesinskieddeb492014-09-08 17:50:03 -07001495 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001496 synchronized (mGuestRestrictions) {
1497 UserRestrictionsUtils
1498 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1499 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301500 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001501 synchronized (mRestrictionsLock) {
1502 UserRestrictionsUtils.writeRestrictions(serializer,
1503 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1504 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001505 int[] userIdsToWrite;
1506 synchronized (mUsersLock) {
1507 userIdsToWrite = new int[mUsers.size()];
1508 for (int i = 0; i < userIdsToWrite.length; i++) {
1509 UserInfo user = mUsers.valueAt(i);
1510 userIdsToWrite[i] = user.id;
1511 }
1512 }
1513 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001514 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001515 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001516 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001517 }
1518
1519 serializer.endTag(null, TAG_USERS);
1520
1521 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001522 userListFile.finishWrite(fos);
1523 } catch (Exception e) {
1524 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001525 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001526 }
1527 }
1528
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001529 private Pair<UserInfo, String> readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001530 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001531 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001532 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001533 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001534 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001535 long creationTime = 0L;
1536 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001537 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001538 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001539 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001540 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001541 Bundle baseRestrictions = new Bundle();
1542 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001543
1544 FileInputStream fis = null;
1545 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001546 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001547 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001548 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001549 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001550 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001551 int type;
1552 while ((type = parser.next()) != XmlPullParser.START_TAG
1553 && type != XmlPullParser.END_DOCUMENT) {
1554 ;
1555 }
1556
1557 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001558 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001559 return null;
1560 }
1561
1562 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001563 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1564 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001565 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001566 return null;
1567 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001568 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1569 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001570 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001571 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1572 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001573 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1574 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001575 restrictedProfileParentId = readIntAttribute(parser,
1576 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001577 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1578 if ("true".equals(valueString)) {
1579 partial = true;
1580 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001581 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1582 if ("true".equals(valueString)) {
1583 guestToRemove = true;
1584 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001585
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001586 int outerDepth = parser.getDepth();
1587 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1588 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1589 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1590 continue;
1591 }
1592 String tag = parser.getName();
1593 if (TAG_NAME.equals(tag)) {
1594 type = parser.next();
1595 if (type == XmlPullParser.TEXT) {
1596 name = parser.getText();
1597 }
1598 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001599 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1600 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1601 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001602 } else if (TAG_ACCOUNT.equals(tag)) {
1603 type = parser.next();
1604 if (type == XmlPullParser.TEXT) {
1605 account = parser.getText();
1606 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001607 }
1608 }
1609 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001610
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001611 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001612 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001613 userInfo.creationTime = creationTime;
1614 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001615 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001616 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001617 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001618 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001619 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001620 mBaseUserRestrictions.put(id, baseRestrictions);
1621 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001622 }
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001623 return new Pair<>(userInfo, account);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001624
1625 } catch (IOException ioe) {
1626 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001627 } finally {
1628 if (fis != null) {
1629 try {
1630 fis.close();
1631 } catch (IOException e) {
1632 }
1633 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001634 }
1635 return null;
1636 }
1637
Amith Yamasani920ace02012-09-20 22:15:37 -07001638 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1639 String valueString = parser.getAttributeValue(null, attr);
1640 if (valueString == null) return defaultValue;
1641 try {
1642 return Integer.parseInt(valueString);
1643 } catch (NumberFormatException nfe) {
1644 return defaultValue;
1645 }
1646 }
1647
1648 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1649 String valueString = parser.getAttributeValue(null, attr);
1650 if (valueString == null) return defaultValue;
1651 try {
1652 return Long.parseLong(valueString);
1653 } catch (NumberFormatException nfe) {
1654 return defaultValue;
1655 }
1656 }
1657
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001658 private boolean isPackageInstalled(String pkg, int userId) {
1659 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1660 PackageManager.GET_UNINSTALLED_PACKAGES,
1661 userId);
1662 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1663 return false;
1664 }
1665 return true;
1666 }
1667
Amith Yamasanib82add22013-07-09 11:24:44 -07001668 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001669 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001670 * Does not do any permissions checking.
1671 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001672 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001673 synchronized (mPackagesLock) {
1674 File dir = Environment.getUserSystemDirectory(userId);
1675 String[] files = dir.list();
1676 if (files == null) return;
1677 for (String fileName : files) {
1678 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1679 File resFile = new File(dir, fileName);
1680 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001681 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001682 }
1683 }
1684 }
1685 }
1686 }
1687
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001688 /**
1689 * Removes the app restrictions file for a specific package and user id, if it exists.
1690 */
1691 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1692 synchronized (mPackagesLock) {
1693 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001694 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001695 if (resFile.exists()) {
1696 resFile.delete();
1697 }
1698 }
1699 }
1700
Kenny Guya52dc3e2014-02-11 15:33:14 +00001701 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001702 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001703 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001704 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001705 }
1706
Amith Yamasani258848d2012-08-10 17:06:33 -07001707 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001708 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001709 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001710 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001711 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001712
Jessica Hummelbe81c802014-04-22 15:49:22 +01001713 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001714 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001715 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1716 return null;
1717 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001718 if (ActivityManager.isLowRamDeviceStatic()) {
1719 return null;
1720 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001721 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001722 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001723 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001724 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001725 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001726 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001727 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001728 synchronized (mPackagesLock) {
1729 UserInfo parent = null;
1730 if (parentId != UserHandle.USER_NULL) {
1731 synchronized (mUsersLock) {
1732 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001733 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001734 if (parent == null) return null;
1735 }
1736 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1737 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1738 return null;
1739 }
1740 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1741 // If we're not adding a guest user or a managed profile and the limit has
1742 // been reached, cannot add a user.
1743 return null;
1744 }
1745 // If we're adding a guest and there already exists one, bail.
1746 if (isGuest && findCurrentGuestUser() != null) {
1747 return null;
1748 }
1749 // In legacy mode, restricted profile's parent can only be the owner user
1750 if (isRestricted && !UserManager.isSplitSystemUser()
1751 && (parentId != UserHandle.USER_SYSTEM)) {
1752 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1753 return null;
1754 }
1755 if (isRestricted && UserManager.isSplitSystemUser()) {
1756 if (parent == null) {
1757 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1758 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001759 return null;
1760 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001761 if (!parent.canHaveProfile()) {
1762 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1763 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001764 return null;
1765 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001766 }
1767 // In split system user mode, we assign the first human user the primary flag.
1768 // And if there is no device owner, we also assign the admin flag to primary user.
1769 if (UserManager.isSplitSystemUser()
1770 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1771 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001772 synchronized (mUsersLock) {
1773 if (!mIsDeviceManaged) {
1774 flags |= UserInfo.FLAG_ADMIN;
1775 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001776 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001777 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001778
1779 if (parent != null && parent.isEphemeral()) {
1780 flags |= UserInfo.FLAG_EPHEMERAL;
1781 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001782 userId = getNextAvailableId();
1783 userInfo = new UserInfo(userId, name, null, flags);
1784 userInfo.serialNumber = mNextSerialNumber++;
1785 long now = System.currentTimeMillis();
1786 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1787 userInfo.partial = true;
1788 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1789 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001790 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001791 }
1792 writeUserListLP();
1793 if (parent != null) {
1794 if (isManagedProfile) {
1795 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1796 parent.profileGroupId = parent.id;
1797 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001798 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001799 userInfo.profileGroupId = parent.profileGroupId;
1800 } else if (isRestricted) {
1801 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1802 parent.restrictedProfileParentId = parent.id;
1803 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001804 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001805 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001806 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001807 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001808 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001809 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001810 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001811 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1812 final String volumeUuid = vol.getFsUuid();
1813 try {
1814 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001815 storage.prepareUserStorage(
1816 volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001817 enforceSerialNumber(userDir, userInfo.serialNumber);
1818 } catch (IOException e) {
1819 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1820 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001821 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001822 mPm.createNewUser(userId);
1823 userInfo.partial = false;
1824 synchronized (mPackagesLock) {
1825 writeUserLP(userInfo);
1826 }
1827 updateUserIds();
1828 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001829 if (isGuest) {
1830 synchronized (mGuestRestrictions) {
1831 restrictions.putAll(mGuestRestrictions);
1832 }
1833 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001834 synchronized (mRestrictionsLock) {
1835 mBaseUserRestrictions.append(userId, restrictions);
1836 }
1837 mPm.newUserCreated(userId);
1838 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1839 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1840 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1841 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001842 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001843 } finally {
1844 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001845 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001846 return userInfo;
1847 }
1848
Amith Yamasani0b285492011-04-14 17:35:23 -07001849 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001850 * @hide
1851 */
1852 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1853 checkManageUsersPermission("setupRestrictedProfile");
1854 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1855 if (user == null) {
1856 return null;
1857 }
1858 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1859 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1860 // the putIntForUser() will fail.
1861 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1862 android.provider.Settings.Secure.LOCATION_MODE,
1863 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1864 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1865 return user;
1866 }
1867
1868 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001869 * Find the current guest user. If the Guest user is partial,
1870 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001871 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001872 private UserInfo findCurrentGuestUser() {
1873 synchronized (mUsersLock) {
1874 final int size = mUsers.size();
1875 for (int i = 0; i < size; i++) {
1876 final UserInfo user = mUsers.valueAt(i);
1877 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1878 return user;
1879 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001880 }
1881 }
1882 return null;
1883 }
1884
1885 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001886 * Mark this guest user for deletion to allow us to create another guest
1887 * and switch to that user before actually removing this guest.
1888 * @param userHandle the userid of the current guest
1889 * @return whether the user could be marked for deletion
1890 */
1891 public boolean markGuestForDeletion(int userHandle) {
1892 checkManageUsersPermission("Only the system can remove users");
1893 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1894 UserManager.DISALLOW_REMOVE_USER, false)) {
1895 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1896 return false;
1897 }
1898
1899 long ident = Binder.clearCallingIdentity();
1900 try {
1901 final UserInfo user;
1902 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001903 synchronized (mUsersLock) {
1904 user = mUsers.get(userHandle);
1905 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1906 return false;
1907 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001908 }
1909 if (!user.isGuest()) {
1910 return false;
1911 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001912 // We set this to a guest user that is to be removed. This is a temporary state
1913 // where we are allowed to add new Guest users, even if this one is still not
1914 // removed. This user will still show up in getUserInfo() calls.
1915 // If we don't get around to removing this Guest user, it will be purged on next
1916 // startup.
1917 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001918 // Mark it as disabled, so that it isn't returned any more when
1919 // profiles are queried.
1920 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001921 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001922 }
1923 } finally {
1924 Binder.restoreCallingIdentity(ident);
1925 }
1926 return true;
1927 }
1928
1929 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001930 * Removes a user and all data directories created for that user. This method should be called
1931 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001932 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001933 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001934 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001935 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001936 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1937 UserManager.DISALLOW_REMOVE_USER, false)) {
1938 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1939 return false;
1940 }
1941
Kenny Guyee58b4f2014-05-23 15:19:53 +01001942 long ident = Binder.clearCallingIdentity();
1943 try {
1944 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001945 int currentUser = ActivityManager.getCurrentUser();
1946 if (currentUser == userHandle) {
1947 Log.w(LOG_TAG, "Current user cannot be removed");
1948 return false;
1949 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001950 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001951 synchronized (mUsersLock) {
1952 user = mUsers.get(userHandle);
1953 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1954 return false;
1955 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001956
Fyodor Kupolov82402752015-10-28 14:54:51 -07001957 // We remember deleted user IDs to prevent them from being
1958 // reused during the current boot; they can still be reused
1959 // after a reboot.
1960 mRemovingUserIds.put(userHandle, true);
1961 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001962
Kenny Guyee58b4f2014-05-23 15:19:53 +01001963 try {
1964 mAppOpsService.removeUser(userHandle);
1965 } catch (RemoteException e) {
1966 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1967 }
1968 // Set this to a partially created user, so that the user will be purged
1969 // on next startup, in case the runtime stops now before stopping and
1970 // removing the user completely.
1971 user.partial = true;
1972 // Mark it as disabled, so that it isn't returned any more when
1973 // profiles are queried.
1974 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001975 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001976 }
1977
1978 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1979 && user.isManagedProfile()) {
1980 // Send broadcast to notify system that the user removed was a
1981 // managed user.
1982 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1983 }
1984
1985 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1986 int res;
1987 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001988 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
1989 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001990 @Override
1991 public void userStopped(int userId) {
1992 finishRemoveUser(userId);
1993 }
1994 @Override
1995 public void userStopAborted(int userId) {
1996 }
1997 });
1998 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001999 return false;
2000 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002001 return res == ActivityManager.USER_OP_SUCCESS;
2002 } finally {
2003 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002004 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002005 }
2006
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002007 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002008 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002009 // Let other services shutdown any activity and clean up their state before completely
2010 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002011 long ident = Binder.clearCallingIdentity();
2012 try {
2013 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2014 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002015 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2016 android.Manifest.permission.MANAGE_USERS,
2017
2018 new BroadcastReceiver() {
2019 @Override
2020 public void onReceive(Context context, Intent intent) {
2021 if (DBG) {
2022 Slog.i(LOG_TAG,
2023 "USER_REMOVED broadcast sent, cleaning up user data "
2024 + userHandle);
2025 }
2026 new Thread() {
2027 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002028 // Clean up any ActivityManager state
2029 LocalServices.getService(ActivityManagerInternal.class)
2030 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002031 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002032 }
2033 }.start();
2034 }
2035 },
2036
2037 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002038 } finally {
2039 Binder.restoreCallingIdentity(ident);
2040 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002041 }
2042
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002043 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002044 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002045 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002046 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002047
2048 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002049 synchronized (mUsersLock) {
2050 mUsers.remove(userHandle);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002051 mUserAccounts.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002052 mIsUserManaged.delete(userHandle);
2053 }
2054 synchronized (mRestrictionsLock) {
2055 mBaseUserRestrictions.remove(userHandle);
2056 mAppliedUserRestrictions.remove(userHandle);
2057 mCachedEffectiveUserRestrictions.remove(userHandle);
2058 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002059 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002060 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002061 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002062 userFile.delete();
2063 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002064 synchronized (mPackagesLock) {
2065 writeUserListLP();
2066 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002067 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002068 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
2069 }
2070
Amith Yamasani61f57372012-08-31 12:12:28 -07002071 private void removeDirectoryRecursive(File parent) {
2072 if (parent.isDirectory()) {
2073 String[] files = parent.list();
2074 for (String filename : files) {
2075 File child = new File(parent, filename);
2076 removeDirectoryRecursive(child);
2077 }
2078 }
2079 parent.delete();
2080 }
2081
Kenny Guyf8d3a232014-05-15 16:09:52 +01002082 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002083 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002084 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2085 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002086 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002087 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002088 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002089 }
2090
Amith Yamasani2a003292012-08-14 18:25:45 -07002091 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002092 public Bundle getApplicationRestrictions(String packageName) {
2093 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2094 }
2095
2096 @Override
2097 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002098 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002099 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002100 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002101 }
2102 synchronized (mPackagesLock) {
2103 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002104 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002105 }
2106 }
2107
2108 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002109 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002110 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002111 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002112 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002113 if (restrictions == null || restrictions.isEmpty()) {
2114 cleanAppRestrictionsForPackage(packageName, userId);
2115 } else {
2116 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002117 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002118 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002119 }
Robin Lee66e5d962014-04-09 16:44:21 +01002120
Kenny Guyd21b2182014-07-17 16:38:55 +01002121 if (isPackageInstalled(packageName, userId)) {
2122 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2123 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2124 changeIntent.setPackage(packageName);
2125 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2126 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2127 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002128 }
2129
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002130 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002131 mHandler.post(new Runnable() {
2132 @Override
2133 public void run() {
2134 List<ApplicationInfo> apps =
2135 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
2136 userHandle).getList();
2137 final long ident = Binder.clearCallingIdentity();
2138 try {
2139 for (ApplicationInfo appInfo : apps) {
2140 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002141 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
2142 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002143 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002144 userHandle);
2145 }
2146 }
2147 } finally {
2148 Binder.restoreCallingIdentity(ident);
2149 }
2150 }
2151 });
2152 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002153 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002154 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002155 try {
2156 return mContext.getPackageManager().getApplicationInfo(packageName,
2157 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2158 } catch (NameNotFoundException nnfe) {
2159 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002160 } finally {
2161 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002162 }
2163 }
2164
Fyodor Kupolov82402752015-10-28 14:54:51 -07002165 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002166 AtomicFile restrictionsFile =
2167 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2168 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002169 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002170 }
2171
2172 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002173 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002174 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002175 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002176 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002177 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002178 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002179
2180 FileInputStream fis = null;
2181 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002182 fis = restrictionsFile.openRead();
2183 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002184 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002185 XmlUtils.nextElement(parser);
2186 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002187 Slog.e(LOG_TAG, "Unable to read restrictions file "
2188 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002189 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002190 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002191 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2192 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002193 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002194 } catch (IOException|XmlPullParserException e) {
2195 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002196 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002197 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002198 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002199 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002200 }
2201
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002202 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2203 XmlPullParser parser) throws XmlPullParserException, IOException {
2204 int type = parser.getEventType();
2205 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2206 String key = parser.getAttributeValue(null, ATTR_KEY);
2207 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2208 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2209 if (multiple != null) {
2210 values.clear();
2211 int count = Integer.parseInt(multiple);
2212 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2213 if (type == XmlPullParser.START_TAG
2214 && parser.getName().equals(TAG_VALUE)) {
2215 values.add(parser.nextText().trim());
2216 count--;
2217 }
2218 }
2219 String [] valueStrings = new String[values.size()];
2220 values.toArray(valueStrings);
2221 restrictions.putStringArray(key, valueStrings);
2222 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2223 restrictions.putBundle(key, readBundleEntry(parser, values));
2224 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2225 final int outerDepth = parser.getDepth();
2226 ArrayList<Bundle> bundleList = new ArrayList<>();
2227 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2228 Bundle childBundle = readBundleEntry(parser, values);
2229 bundleList.add(childBundle);
2230 }
2231 restrictions.putParcelableArray(key,
2232 bundleList.toArray(new Bundle[bundleList.size()]));
2233 } else {
2234 String value = parser.nextText().trim();
2235 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2236 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2237 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2238 restrictions.putInt(key, Integer.parseInt(value));
2239 } else {
2240 restrictions.putString(key, value);
2241 }
2242 }
2243 }
2244 }
2245
2246 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2247 throws IOException, XmlPullParserException {
2248 Bundle childBundle = new Bundle();
2249 final int outerDepth = parser.getDepth();
2250 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2251 readEntry(childBundle, values, parser);
2252 }
2253 return childBundle;
2254 }
2255
Fyodor Kupolov82402752015-10-28 14:54:51 -07002256 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002257 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002258 AtomicFile restrictionsFile = new AtomicFile(
2259 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002260 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002261 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002262 }
2263
2264 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002265 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002266 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002267 try {
2268 fos = restrictionsFile.startWrite();
2269 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2270
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002271 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002272 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002273 serializer.startDocument(null, true);
2274 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2275
2276 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002277 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002278 serializer.endTag(null, TAG_RESTRICTIONS);
2279
2280 serializer.endDocument();
2281 restrictionsFile.finishWrite(fos);
2282 } catch (Exception e) {
2283 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002284 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2285 }
2286 }
2287
2288 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2289 throws IOException {
2290 for (String key : restrictions.keySet()) {
2291 Object value = restrictions.get(key);
2292 serializer.startTag(null, TAG_ENTRY);
2293 serializer.attribute(null, ATTR_KEY, key);
2294
2295 if (value instanceof Boolean) {
2296 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2297 serializer.text(value.toString());
2298 } else if (value instanceof Integer) {
2299 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2300 serializer.text(value.toString());
2301 } else if (value == null || value instanceof String) {
2302 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2303 serializer.text(value != null ? (String) value : "");
2304 } else if (value instanceof Bundle) {
2305 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2306 writeBundle((Bundle) value, serializer);
2307 } else if (value instanceof Parcelable[]) {
2308 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2309 Parcelable[] array = (Parcelable[]) value;
2310 for (Parcelable parcelable : array) {
2311 if (!(parcelable instanceof Bundle)) {
2312 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2313 }
2314 serializer.startTag(null, TAG_ENTRY);
2315 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2316 writeBundle((Bundle) parcelable, serializer);
2317 serializer.endTag(null, TAG_ENTRY);
2318 }
2319 } else {
2320 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2321 String[] values = (String[]) value;
2322 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2323 for (String choice : values) {
2324 serializer.startTag(null, TAG_VALUE);
2325 serializer.text(choice != null ? choice : "");
2326 serializer.endTag(null, TAG_VALUE);
2327 }
2328 }
2329 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002330 }
2331 }
2332
2333 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002334 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002335 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002336 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002337 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002338 }
2339 }
2340
2341 @Override
2342 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002343 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002344 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002345 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002346 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002347 }
2348 // Not found
2349 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002350 }
2351 }
2352
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002353 @Override
2354 public long getUserCreationTime(int userHandle) {
2355 int callingUserId = UserHandle.getCallingUserId();
2356 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002357 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002358 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002359 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002360 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002361 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002362 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002363 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002364 }
2365 }
2366 }
2367 if (userInfo == null) {
2368 throw new SecurityException("userHandle can only be the calling user or a managed "
2369 + "profile associated with this user");
2370 }
2371 return userInfo.creationTime;
2372 }
2373
Amith Yamasani0b285492011-04-14 17:35:23 -07002374 /**
2375 * Caches the list of user ids in an array, adjusting the array size when necessary.
2376 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002377 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002378 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002379 synchronized (mUsersLock) {
2380 final int userSize = mUsers.size();
2381 for (int i = 0; i < userSize; i++) {
2382 if (!mUsers.valueAt(i).partial) {
2383 num++;
2384 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002385 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002386 final int[] newUsers = new int[num];
2387 int n = 0;
2388 for (int i = 0; i < userSize; i++) {
2389 if (!mUsers.valueAt(i).partial) {
2390 newUsers[n++] = mUsers.keyAt(i);
2391 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002392 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002393 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002394 }
2395 }
2396
2397 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002398 * Called right before a user is started. This gives us a chance to prepare
2399 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002400 */
2401 public void onBeforeStartUser(int userId) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002402 mPm.reconcileAppsData(userId, Installer.FLAG_DE_STORAGE);
2403
2404 if (userId != UserHandle.USER_SYSTEM) {
2405 synchronized (mRestrictionsLock) {
2406 applyUserRestrictionsLR(userId);
2407 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002408 }
2409 }
2410
2411 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002412 * Called right before a user is unlocked. This gives us a chance to prepare
2413 * app storage.
2414 */
2415 public void onBeforeUnlockUser(int userId) {
2416 mPm.reconcileAppsData(userId, Installer.FLAG_CE_STORAGE);
2417 }
2418
2419 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002420 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002421 * @param userId the user that was just foregrounded
2422 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002423 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002424 UserInfo user = getUserInfoNoChecks(userId);
2425 if (user == null || user.partial) {
2426 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2427 return;
2428 }
2429 long now = System.currentTimeMillis();
2430 if (now > EPOCH_PLUS_30_YEARS) {
2431 user.lastLoggedInTime = now;
2432 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002433 }
2434 }
2435
2436 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002437 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002438 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2439 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002440 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002441 private int getNextAvailableId() {
2442 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002443 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002444 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002445 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002446 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002447 }
2448 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002449 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002450 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002451 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002452 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002453
Amith Yamasanifc95e702013-09-26 13:20:17 -07002454 private String packageToRestrictionsFileName(String packageName) {
2455 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2456 }
2457
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002458 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002459 * Enforce that serial number stored in user directory inode matches the
2460 * given expected value. Gracefully sets the serial number if currently
2461 * undefined.
2462 *
2463 * @throws IOException when problem extracting serial number, or serial
2464 * number is mismatched.
2465 */
2466 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2467 final int foundSerial = getSerialNumber(file);
2468 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2469
2470 if (foundSerial == -1) {
2471 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2472 try {
2473 setSerialNumber(file, serialNumber);
2474 } catch (IOException e) {
2475 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2476 }
2477
2478 } else if (foundSerial != serialNumber) {
2479 throw new IOException("Found serial number " + foundSerial
2480 + " doesn't match expected " + serialNumber);
2481 }
2482 }
2483
2484 /**
2485 * Set serial number stored in user directory inode.
2486 *
2487 * @throws IOException if serial number was already set
2488 */
2489 private static void setSerialNumber(File file, int serialNumber)
2490 throws IOException {
2491 try {
2492 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2493 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2494 } catch (ErrnoException e) {
2495 throw e.rethrowAsIOException();
2496 }
2497 }
2498
2499 /**
2500 * Return serial number stored in user directory inode.
2501 *
2502 * @return parsed serial number, or -1 if not set
2503 */
2504 private static int getSerialNumber(File file) throws IOException {
2505 try {
2506 final byte[] buf = new byte[256];
2507 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2508 final String serial = new String(buf, 0, len);
2509 try {
2510 return Integer.parseInt(serial);
2511 } catch (NumberFormatException e) {
2512 throw new IOException("Bad serial number: " + serial);
2513 }
2514 } catch (ErrnoException e) {
2515 if (e.errno == OsConstants.ENODATA) {
2516 return -1;
2517 } else {
2518 throw e.rethrowAsIOException();
2519 }
2520 }
2521 }
2522
Amith Yamasani920ace02012-09-20 22:15:37 -07002523 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002524 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2525 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2526 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2527 }
2528
2529 int onShellCommand(Shell shell, String cmd) {
2530 if (cmd == null) {
2531 return shell.handleDefaultCommands(cmd);
2532 }
2533
2534 final PrintWriter pw = shell.getOutPrintWriter();
2535 try {
2536 switch(cmd) {
2537 case "list":
2538 return runList(pw);
2539 }
2540 } catch (RemoteException e) {
2541 pw.println("Remote exception: " + e);
2542 }
2543 return -1;
2544 }
2545
2546 private int runList(PrintWriter pw) throws RemoteException {
2547 final IActivityManager am = ActivityManagerNative.getDefault();
2548 final List<UserInfo> users = getUsers(false);
2549 if (users == null) {
2550 pw.println("Error: couldn't get users");
2551 return 1;
2552 } else {
2553 pw.println("Users:");
2554 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002555 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002556 pw.println("\t" + users.get(i).toString() + running);
2557 }
2558 return 0;
2559 }
2560 }
2561
2562 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002563 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2564 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2565 != PackageManager.PERMISSION_GRANTED) {
2566 pw.println("Permission Denial: can't dump UserManager from from pid="
2567 + Binder.getCallingPid()
2568 + ", uid=" + Binder.getCallingUid()
2569 + " without permission "
2570 + android.Manifest.permission.DUMP);
2571 return;
2572 }
2573
2574 long now = System.currentTimeMillis();
2575 StringBuilder sb = new StringBuilder();
2576 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002577 synchronized (mUsersLock) {
2578 pw.println("Users:");
2579 for (int i = 0; i < mUsers.size(); i++) {
2580 UserInfo user = mUsers.valueAt(i);
2581 if (user == null) {
2582 continue;
2583 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002584 final int userId = user.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002585 pw.print(" "); pw.print(user);
2586 pw.print(" serialNo="); pw.print(user.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002587 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002588 pw.print(" <removing> ");
2589 }
2590 if (user.partial) {
2591 pw.print(" <partial>");
2592 }
2593 pw.println();
2594 pw.print(" Created: ");
2595 if (user.creationTime == 0) {
2596 pw.println("<unknown>");
2597 } else {
2598 sb.setLength(0);
2599 TimeUtils.formatDuration(now - user.creationTime, sb);
2600 sb.append(" ago");
2601 pw.println(sb);
2602 }
2603 pw.print(" Last logged in: ");
2604 if (user.lastLoggedInTime == 0) {
2605 pw.println("<unknown>");
2606 } else {
2607 sb.setLength(0);
2608 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2609 sb.append(" ago");
2610 pw.println(sb);
2611 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002612 pw.print(" Has profile owner: ");
2613 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002614 pw.println(" Restrictions:");
2615 synchronized (mRestrictionsLock) {
2616 UserRestrictionsUtils.dumpRestrictions(
2617 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002618 pw.println(" Device policy local restrictions:");
2619 UserRestrictionsUtils.dumpRestrictions(
2620 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002621 pw.println(" Effective restrictions:");
2622 UserRestrictionsUtils.dumpRestrictions(
2623 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2624 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002625 pw.println();
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002626 String accountName = mUserAccounts.get(userId);
2627 if (accountName != null) {
2628 pw.print(" Account name: " + accountName);
2629 pw.println();
2630 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002631 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002632 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002633 pw.println(" Device policy global restrictions:");
2634 synchronized (mRestrictionsLock) {
2635 UserRestrictionsUtils
2636 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2637 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002638 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002639 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002640 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002641 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002642 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002643 synchronized (mUsersLock) {
2644 pw.println();
2645 pw.println(" Device managed: " + mIsDeviceManaged);
2646 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002647 }
2648 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002649
2650 final class MainHandler extends Handler {
2651
2652 @Override
2653 public void handleMessage(Message msg) {
2654 switch (msg.what) {
2655 case WRITE_USER_MSG:
2656 removeMessages(WRITE_USER_MSG, msg.obj);
2657 synchronized (mPackagesLock) {
2658 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002659 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002660 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002661 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002662 }
2663 }
2664 }
2665 }
2666 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002667
2668 /**
2669 * @param userId
2670 * @return whether the user has been initialized yet
2671 */
2672 boolean isInitialized(int userId) {
2673 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2674 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002675
2676 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002677 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002678 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2679 @Nullable Bundle globalRestrictions) {
2680 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2681 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002682 }
2683
2684 @Override
2685 public Bundle getBaseUserRestrictions(int userId) {
2686 synchronized (mRestrictionsLock) {
2687 return mBaseUserRestrictions.get(userId);
2688 }
2689 }
2690
2691 @Override
2692 public void setBaseUserRestrictionsByDpmsForMigration(
2693 int userId, Bundle baseRestrictions) {
2694 synchronized (mRestrictionsLock) {
2695 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002696 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002697 }
2698
Fyodor Kupolov82402752015-10-28 14:54:51 -07002699 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002700 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002701 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002702 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002703 } else {
2704 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2705 }
2706 }
2707 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002708
2709 @Override
2710 public boolean getUserRestriction(int userId, String key) {
2711 return getUserRestrictions(userId).getBoolean(key);
2712 }
2713
2714 @Override
2715 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2716 synchronized (mUserRestrictionsListeners) {
2717 mUserRestrictionsListeners.add(listener);
2718 }
2719 }
2720
2721 @Override
2722 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2723 synchronized (mUserRestrictionsListeners) {
2724 mUserRestrictionsListeners.remove(listener);
2725 }
2726 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002727
2728 @Override
2729 public void setDeviceManaged(boolean isManaged) {
2730 synchronized (mUsersLock) {
2731 mIsDeviceManaged = isManaged;
2732 }
2733 }
2734
2735 @Override
2736 public void setUserManaged(int userId, boolean isManaged) {
2737 synchronized (mUsersLock) {
2738 mIsUserManaged.put(userId, isManaged);
2739 }
2740 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002741 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002742
2743 private class Shell extends ShellCommand {
2744 @Override
2745 public int onCommand(String cmd) {
2746 return onShellCommand(this, cmd);
2747 }
2748
2749 @Override
2750 public void onHelp() {
2751 final PrintWriter pw = getOutPrintWriter();
2752 pw.println("User manager (user) commands:");
2753 pw.println(" help");
2754 pw.println(" Print this help text.");
2755 pw.println("");
2756 pw.println(" list");
2757 pw.println(" Prints all users on the system.");
2758 }
2759 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002760
2761 private static void debug(String message) {
2762 Log.d(LOG_TAG, message +
2763 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2764 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002765}