blob: 1e5245cfd81c97ca331b1722b5bfd7d24c0ba310 [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
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Andrew Scull85a63bc2016-10-24 13:47:47 +010029import android.app.ActivityManagerNative;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000030import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010034import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070040import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080041import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070042import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010043import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070044import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060046import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080047import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080048import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.os.Environment;
50import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080052import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070053import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080054import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010055import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070056import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080057import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070058import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070059import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070060import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010061import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040062import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070063import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070064import android.os.ShellCommand;
Kenny Guy02c89902016-11-15 19:36:38 +000065import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070067import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010068import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080070import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010071import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070072import android.security.GateKeeper;
73import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070074import android.system.ErrnoException;
75import android.system.Os;
76import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070077import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070078import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070079import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070080import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import android.util.Slog;
82import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080083import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000084import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070085import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import android.util.Xml;
87
Makoto Onuki068c54a2015-10-13 14:34:03 -070088import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040090import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080091import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060092import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080093import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070094import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070095import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000096import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070097import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060098import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070099import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000100import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700101import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100102
Jeff Sharkey47f71082016-02-01 17:03:54 -0700103import libcore.io.IoUtils;
104import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800105
106import org.xmlpull.v1.XmlPullParser;
107import org.xmlpull.v1.XmlPullParserException;
108import org.xmlpull.v1.XmlSerializer;
109
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110import java.io.BufferedOutputStream;
111import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700112import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700114import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115import java.io.FileOutputStream;
Kenny Guy02c89902016-11-15 19:36:38 +0000116import java.io.InputStream;
117import java.io.OutputStream;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700119import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100120import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100122import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700123import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124import java.util.List;
125
Makoto Onuki068c54a2015-10-13 14:34:03 -0700126/**
127 * Service for {@link UserManager}.
128 *
129 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700130 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700131 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800132 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700133 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
134 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
135 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700136 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700137public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700138
Amith Yamasani2a003292012-08-14 18:25:45 -0700139 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800140 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800141 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700142 // Can be used for manual testing of id recycling
143 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700144
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800146 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700148 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700149 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700150 private static final String ATTR_CREATION_TIME = "created";
151 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600152 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700153 private static final String ATTR_SERIAL_NO = "serialNumber";
154 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700155 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700156 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700157 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100158 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000159 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700160 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800161 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
162 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530163 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700164 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700165 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800166 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800167 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100168 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
169 "device_policy_global_restrictions";
170 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100171 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100172 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800173 private static final String TAG_ENTRY = "entry";
174 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800175 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800176 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700177 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800178 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700179
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700180 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
181 private static final String ATTR_TYPE_STRING = "s";
182 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700183 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700184 private static final String ATTR_TYPE_BUNDLE = "B";
185 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700186
Amith Yamasani0b285492011-04-14 17:35:23 -0700187 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700189 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100190 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800192 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700193 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800194
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700195 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
196 UserInfo.FLAG_MANAGED_PROFILE
197 | UserInfo.FLAG_EPHEMERAL
198 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700199 | UserInfo.FLAG_GUEST
200 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700201
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700202 @VisibleForTesting
203 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700204 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700205 @VisibleForTesting
206 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
207
208 // Max size of the queue of recently removed users
209 @VisibleForTesting
210 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700211
Pavel Grafov6a40f092016-10-25 15:46:51 +0100212 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700213
Amith Yamasani920ace02012-09-20 22:15:37 -0700214 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
215
Nicolas Prevotb8186812015-08-06 15:00:03 +0100216 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700217 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000218 @VisibleForTesting
219 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700220
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800221 static final int WRITE_USER_MSG = 1;
222 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530223
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800224 // Tron counters
225 private static final String TRON_GUEST_CREATED = "users_guest_created";
226 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700227 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800228
Dianne Hackborn4428e172012-08-24 17:43:05 -0700229 private final Context mContext;
230 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700231 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800232 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700233 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600234 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700235 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700236 // Used for serializing access to app restriction files
237 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700238
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800239 private final Handler mHandler;
240
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700241 private final File mUsersDir;
242 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700243
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800244 private static final IBinder mUserRestriconToken = new Binder();
245
Makoto Onuki068c54a2015-10-13 14:34:03 -0700246 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800247 * User-related information that is used for persisting to flash. Only UserInfo is
248 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800249 */
Kenny Guy02c89902016-11-15 19:36:38 +0000250 @VisibleForTesting
251 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800252 // Basic user information and properties
253 UserInfo info;
254 // Account name used when there is a strong association between a user and an account
255 String account;
256 // Account information for seeding into a newly created user. This could also be
257 // used for login validation for an existing user, for updating their credentials.
258 // In the latter case, data may not need to be persisted as it is only valid for the
259 // current login session.
260 String seedAccountName;
261 String seedAccountType;
262 PersistableBundle seedAccountOptions;
263 // Whether to perist the seed account information to be available after a boot
264 boolean persistSeedData;
265
266 void clearSeedAccountData() {
267 seedAccountName = null;
268 seedAccountType = null;
269 seedAccountOptions = null;
270 persistSeedData = false;
271 }
272 }
273
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800274 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800275 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800276
277 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700278 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100279 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700280 *
281 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
282 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
283 * maybe shared between {@link #mBaseUserRestrictions} and
284 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
285 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700286 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700287 */
288 @GuardedBy("mRestrictionsLock")
289 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
290
291 /**
292 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
293 * with device / profile owner restrictions. We'll initialize it lazily; use
294 * {@link #getEffectiveUserRestrictions} to access it.
295 *
296 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
297 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
298 * maybe shared between {@link #mBaseUserRestrictions} and
299 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
300 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700301 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700302 */
303 @GuardedBy("mRestrictionsLock")
304 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
305
Makoto Onuki4f160732015-10-27 17:15:38 -0700306 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800307 * User restrictions that have already been applied in
308 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
309 * that have changed since the last
310 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700311 */
312 @GuardedBy("mRestrictionsLock")
313 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
314
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800315 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800316 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100317 * that should be applied to all users, including guests. Only non-empty restriction bundles are
318 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800319 */
320 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100321 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800322
323 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100324 * Id of the user that set global restrictions.
325 */
326 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100327 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100328
329 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800330 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100331 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800332 */
333 @GuardedBy("mRestrictionsLock")
334 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
335
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800336 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530337 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800338
339 /**
340 * Set of user IDs being actively removed. Removed IDs linger in this set
341 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700342 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800343 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700344 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800345 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700346
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700347 /**
348 * Queue of recently removed userIds. Used for recycling of userIds
349 */
350 @GuardedBy("mUsersLock")
351 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
352
Fyodor Kupolov82402752015-10-28 14:54:51 -0700353 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700354 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800355 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700356 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700357 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700358
Jason Monk62062992014-05-06 09:55:28 -0400359 private IAppOpsService mAppOpsService;
360
Makoto Onuki068c54a2015-10-13 14:34:03 -0700361 private final LocalService mLocalService;
362
Makoto Onukie7927da2015-11-25 10:05:17 -0800363 @GuardedBy("mUsersLock")
364 private boolean mIsDeviceManaged;
365
366 @GuardedBy("mUsersLock")
367 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
368
Makoto Onukid45a4a22015-11-02 17:17:38 -0800369 @GuardedBy("mUserRestrictionsListeners")
370 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
371 new ArrayList<>();
372
Clara Bayarria1771112015-12-18 16:29:18 +0000373 private final LockPatternUtils mLockPatternUtils;
374
Ricky Waib1dd80b2016-06-07 18:00:55 +0100375 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
376 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
377
378 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
379 @Override
380 public void onReceive(Context context, Intent intent) {
381 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
382 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
383 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
384 setQuietModeEnabled(userHandle, false);
385 if (target != null) {
386 try {
387 mContext.startIntentSender(target, null, 0, 0, 0);
388 } catch (IntentSender.SendIntentException e) {
389 /* ignore */
390 }
391 }
392 }
393 }
394 };
395
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100396 /**
397 * Whether all users should be created ephemeral.
398 */
399 @GuardedBy("mUsersLock")
400 private boolean mForceEphemeralUsers;
401
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000402 @GuardedBy("mUserStates")
403 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700404
Amith Yamasani258848d2012-08-10 17:06:33 -0700405 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700406
Dianne Hackborn4428e172012-08-24 17:43:05 -0700407 public static UserManagerService getInstance() {
408 synchronized (UserManagerService.class) {
409 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700410 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700411 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700412
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700413 public static class LifeCycle extends SystemService {
414
415 private UserManagerService mUms;
416
417 /**
418 * @param context
419 */
420 public LifeCycle(Context context) {
421 super(context);
422 }
423
424 @Override
425 public void onStart() {
426 mUms = UserManagerService.getInstance();
427 publishBinderService(Context.USER_SERVICE, mUms);
428 }
429
430 @Override
431 public void onBootPhase(int phase) {
432 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
433 mUms.cleanupPartialUsers();
434 }
435 }
436 }
437
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700438 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800439 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700440 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800441 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700442 }
443
Dianne Hackborn4428e172012-08-24 17:43:05 -0700444 /**
445 * Called by package manager to create the service. This is closely
446 * associated with the package manager, and the given lock is the
447 * package manager's own lock.
448 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800449 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
450 Object packagesLock) {
451 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700452 }
453
Dianne Hackborn4428e172012-08-24 17:43:05 -0700454 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800455 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700456 mContext = context;
457 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700458 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800459 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800460 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800461 synchronized (mPackagesLock) {
462 mUsersDir = new File(dataDir, USER_INFO_DIR);
463 mUsersDir.mkdirs();
464 // Make zeroth user directory, for services to migrate their files to that location
465 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
466 userZeroDir.mkdirs();
467 FileUtils.setPermissions(mUsersDir.toString(),
468 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
469 -1, -1);
470 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
471 initDefaultGuestRestrictions();
472 readUserListLP();
473 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700474 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700475 mLocalService = new LocalService();
476 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000477 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000478 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700479 }
480
481 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400482 mAppOpsService = IAppOpsService.Stub.asInterface(
483 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800484
485 synchronized (mRestrictionsLock) {
486 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400487 }
Samuel Tand9453b82016-03-14 15:57:02 -0700488
489 UserInfo currentGuestUser = findCurrentGuestUser();
490 if (currentGuestUser != null && !hasUserRestriction(
491 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
492 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
493 // to it, in case this guest was created in a previous version where this
494 // user restriction was not a default guest restriction.
495 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
496 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700497
Ricky Waib1dd80b2016-06-07 18:00:55 +0100498 mContext.registerReceiver(mDisableQuietModeCallback,
499 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
500 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700501 }
502
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700503 void cleanupPartialUsers() {
504 // Prune out any partially created, partially removed and ephemeral users.
505 ArrayList<UserInfo> partials = new ArrayList<>();
506 synchronized (mUsersLock) {
507 final int userSize = mUsers.size();
508 for (int i = 0; i < userSize; i++) {
509 UserInfo ui = mUsers.valueAt(i).info;
510 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
511 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700512 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700513 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700514 }
515 }
516 }
517 final int partialsSize = partials.size();
518 for (int i = 0; i < partialsSize; i++) {
519 UserInfo ui = partials.get(i);
520 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
521 + " (name=" + ui.name + ")");
522 removeUserState(ui.id);
523 }
524 }
525
Amith Yamasani258848d2012-08-10 17:06:33 -0700526 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800527 public String getUserAccount(int userId) {
528 checkManageUserAndAcrossUsersFullPermission("get user account");
529 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800530 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800531 }
532 }
533
534 @Override
535 public void setUserAccount(int userId, String accountName) {
536 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800537 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800538 synchronized (mPackagesLock) {
539 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800540 final UserData userData = mUsers.get(userId);
541 if (userData == null) {
542 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
543 return;
544 }
545 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800546 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800547 userData.account = accountName;
548 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800549 }
550 }
551
552 if (userToUpdate != null) {
553 writeUserLP(userToUpdate);
554 }
555 }
556 }
557
558 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700559 public UserInfo getPrimaryUser() {
560 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700561 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700562 final int userSize = mUsers.size();
563 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800564 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800565 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700566 return ui;
567 }
568 }
569 }
570 return null;
571 }
572
573 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700574 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700575 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700576 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700577 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700578 final int userSize = mUsers.size();
579 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800580 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700581 if (ui.partial) {
582 continue;
583 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800584 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700585 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700586 }
Amith Yamasani13593602012-03-22 16:16:17 -0700587 }
588 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700589 }
Amith Yamasani13593602012-03-22 16:16:17 -0700590 }
591
Amith Yamasani258848d2012-08-10 17:06:33 -0700592 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100593 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700594 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800595 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700596 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700597 } else {
598 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800599 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700600 final long ident = Binder.clearCallingIdentity();
601 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700602 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700603 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100604 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700605 } finally {
606 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000607 }
608 }
609
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700610 @Override
611 public int[] getProfileIds(int userId, boolean enabledOnly) {
612 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700613 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700614 }
615 final long ident = Binder.clearCallingIdentity();
616 try {
617 synchronized (mUsersLock) {
618 return getProfileIdsLU(userId, enabledOnly).toArray();
619 }
620 } finally {
621 Binder.restoreCallingIdentity(ident);
622 }
623 }
624
Amith Yamasanibe465322014-04-24 13:45:17 -0700625 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700626 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700627 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
628 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
629 for (int i = 0; i < profileIds.size(); i++) {
630 int profileId = profileIds.get(i);
631 UserInfo userInfo = mUsers.get(profileId).info;
632 // If full info is not required - clear PII data to prevent 3P apps from reading it
633 if (!fullInfo) {
634 userInfo = new UserInfo(userInfo);
635 userInfo.name = null;
636 userInfo.iconPath = null;
637 } else {
638 userInfo = userWithName(userInfo);
639 }
640 users.add(userInfo);
641 }
642 return users;
643 }
644
645 /**
646 * Assume permissions already checked and caller's identity cleared
647 */
648 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700649 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700650 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700651 if (user == null) {
652 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700653 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700654 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700655 final int userSize = mUsers.size();
656 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800657 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700658 if (!isProfileOf(user, profile)) {
659 continue;
660 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100661 if (enabledOnly && !profile.isEnabled()) {
662 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700663 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700664 if (mRemovingUserIds.get(profile.id)) {
665 continue;
666 }
Tony Mak80189cd2016-04-05 17:21:42 +0100667 if (profile.partial) {
668 continue;
669 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700670 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700671 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700672 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700673 }
674
Jessica Hummelbe81c802014-04-22 15:49:22 +0100675 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700676 public int getCredentialOwnerProfile(int userHandle) {
677 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000678 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700679 synchronized (mUsersLock) {
680 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700681 if (profileParent != null) {
682 return profileParent.id;
683 }
684 }
685 }
686
687 return userHandle;
688 }
689
690 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700691 public boolean isSameProfileGroup(int userId, int otherUserId) {
692 if (userId == otherUserId) return true;
693 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700694 return isSameProfileGroupNoChecks(userId, otherUserId);
695 }
696
697 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700698 synchronized (mUsersLock) {
699 UserInfo userInfo = getUserInfoLU(userId);
700 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
701 return false;
702 }
703 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
704 if (otherUserInfo == null
705 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
706 return false;
707 }
708 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700709 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700710 }
711
712 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100713 public UserInfo getProfileParent(int userHandle) {
714 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700715 synchronized (mUsersLock) {
716 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700717 }
718 }
719
Fyodor Kupolov82402752015-10-28 14:54:51 -0700720 private UserInfo getProfileParentLU(int userHandle) {
721 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700722 if (profile == null) {
723 return null;
724 }
725 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800726 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700727 return null;
728 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700729 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100730 }
731 }
732
Fyodor Kupolov82402752015-10-28 14:54:51 -0700733 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100734 return user.id == profile.id ||
735 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
736 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000737 }
738
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000739 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000740 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100741 Intent intent = new Intent();
742 if (inQuietMode) {
743 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
744 } else {
745 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
746 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000747 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
748 intent.putExtra(Intent.EXTRA_USER, profileHandle);
749 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000750 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000751 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000752 }
753
754 @Override
755 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
756 checkManageUsersPermission("silence profile");
757 boolean changed = false;
758 UserInfo profile, parent;
759 synchronized (mPackagesLock) {
760 synchronized (mUsersLock) {
761 profile = getUserInfoLU(userHandle);
762 parent = getProfileParentLU(userHandle);
763
764 }
765 if (profile == null || !profile.isManagedProfile()) {
766 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
767 }
768 if (profile.isQuietModeEnabled() != enableQuietMode) {
769 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800770 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000771 changed = true;
772 }
773 }
774 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000775 long identity = Binder.clearCallingIdentity();
776 try {
777 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800778 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100779 LocalServices.getService(ActivityManagerInternal.class)
780 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000781 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800782 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000783 }
784 } catch (RemoteException e) {
785 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
786 } finally {
787 Binder.restoreCallingIdentity(identity);
788 }
789
790 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
791 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000792 }
793 }
794
795 @Override
796 public boolean isQuietModeEnabled(int userHandle) {
797 synchronized (mPackagesLock) {
798 UserInfo info;
799 synchronized (mUsersLock) {
800 info = getUserInfoLU(userHandle);
801 }
802 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000803 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000804 }
805 return info.isQuietModeEnabled();
806 }
807 }
808
Kenny Guya52dc3e2014-02-11 15:33:14 +0000809 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100810 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100811 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600812 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100813 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100814 // if the user is already unlocked, no need to show a profile challenge
815 setQuietModeEnabled(userHandle, false);
816 return true;
817 }
818
819 long identity = Binder.clearCallingIdentity();
820 try {
821 // otherwise, we show a profile challenge to trigger decryption of the user
822 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
823 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100824 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
825 // lock, confirm screenlock page will know and show personal challenge, and unlock
826 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100827 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
828 userHandle);
829 if (unlockIntent == null) {
830 return false;
831 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100832 final Intent callBackIntent = new Intent(
833 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100834 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100835 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100836 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100837 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
838 callBackIntent.setPackage(mContext.getPackageName());
839 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
840 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
841 mContext,
842 0,
843 callBackIntent,
844 PendingIntent.FLAG_CANCEL_CURRENT |
845 PendingIntent.FLAG_ONE_SHOT |
846 PendingIntent.FLAG_IMMUTABLE);
847 // After unlocking the challenge, it will disable quiet mode and run the original
848 // intentSender
849 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100850 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
851 mContext.startActivity(unlockIntent);
852 } finally {
853 Binder.restoreCallingIdentity(identity);
854 }
855 return false;
856 }
857
858 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100859 public void setUserEnabled(int userId) {
860 checkManageUsersPermission("enable user");
861 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700862 UserInfo info;
863 synchronized (mUsersLock) {
864 info = getUserInfoLU(userId);
865 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100866 if (info != null && !info.isEnabled()) {
867 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800868 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100869 }
870 }
871 }
872
Andrew Scull85a63bc2016-10-24 13:47:47 +0100873 /**
874 * Evicts a user's CE key by stopping and restarting the user.
875 *
876 * The key is evicted automatically by the user controller when the user has stopped.
877 */
878 @Override
879 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
880 checkManageUsersPermission("evict CE key");
881 final IActivityManager am = ActivityManagerNative.getDefault();
882 final long identity = Binder.clearCallingIdentity();
883 try {
884 am.restartUserInBackground(userId);
885 } catch (RemoteException re) {
886 throw re.rethrowAsRuntimeException();
887 } finally {
888 Binder.restoreCallingIdentity(identity);
889 }
890 }
891
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100892 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700893 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700894 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000895 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700896 return userWithName(getUserInfoLU(userId));
897 }
898 }
899
900 /**
901 * Returns a UserInfo object with the name filled in, for Owner, or the original
902 * if the name is already set.
903 */
904 private UserInfo userWithName(UserInfo orig) {
905 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
906 UserInfo withName = new UserInfo(orig);
907 withName.name = getOwnerName();
908 return withName;
909 } else {
910 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000911 }
912 }
913
914 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000915 public int getManagedProfileBadge(@UserIdInt int userId) {
916 int callingUserId = UserHandle.getCallingUserId();
917 if (callingUserId != userId && !hasManageUsersPermission()) {
918 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
919 throw new SecurityException(
920 "You need MANAGE_USERS permission to: check if specified user a " +
921 "managed profile outside your profile group");
922 }
923 }
924 synchronized (mUsersLock) {
925 UserInfo userInfo = getUserInfoLU(userId);
926 return userInfo != null ? userInfo.profileBadge : 0;
927 }
928 }
929
930 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000931 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000932 int callingUserId = UserHandle.getCallingUserId();
933 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700934 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700935 throw new SecurityException(
936 "You need MANAGE_USERS permission to: check if specified user a " +
937 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000938 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000939 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700940 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700941 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000942 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700943 }
944 }
945
Amith Yamasani71e6c692013-03-24 17:39:28 -0700946 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700947 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800948 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700949 return mLocalService.isUserUnlockingOrUnlocked(userId);
950 }
951
952 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800953 public boolean isUserUnlocked(int userId) {
954 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -0700955 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800956 }
957
958 @Override
959 public boolean isUserRunning(int userId) {
960 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
961 return mLocalService.isUserRunning(userId);
962 }
963
964 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
965 int callingUserId = UserHandle.getCallingUserId();
966 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
967 hasManageUsersPermission()) {
968 return;
969 }
970 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
971 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
972 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
973 + "to: check " + name);
974 }
975 }
976
977 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700978 public boolean isDemoUser(int userId) {
979 int callingUserId = UserHandle.getCallingUserId();
980 if (callingUserId != userId && !hasManageUsersPermission()) {
981 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
982 + " is a demo user");
983 }
984 synchronized (mUsersLock) {
985 UserInfo userInfo = getUserInfoLU(userId);
986 return userInfo != null && userInfo.isDemo();
987 }
988 }
989
990 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700991 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700992 synchronized (mUsersLock) {
993 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700994 }
995 }
996
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700997 @Override
998 public boolean canHaveRestrictedProfile(int userId) {
999 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001000 synchronized (mUsersLock) {
1001 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001002 if (userInfo == null || !userInfo.canHaveProfile()) {
1003 return false;
1004 }
1005 if (!userInfo.isAdmin()) {
1006 return false;
1007 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001008 // restricted profile can be created if there is no DO set and the admin user has no PO;
1009 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001010 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001011 }
1012
Amith Yamasani195263742012-08-21 15:40:12 -07001013 /*
1014 * Should be locked on mUsers before calling this.
1015 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001016 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001017 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001018 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001019 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001020 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1021 return null;
1022 }
Amith Yamasani12747872015-12-07 14:19:49 -08001023 return userData != null ? userData.info : null;
1024 }
1025
1026 private UserData getUserDataLU(int userId) {
1027 final UserData userData = mUsers.get(userId);
1028 // If it is partial and not in the process of being removed, return as unknown user.
1029 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1030 return null;
1031 }
1032 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001033 }
1034
Fyodor Kupolov82402752015-10-28 14:54:51 -07001035 /**
1036 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1037 * <p>No permissions checking or any addition checks are made</p>
1038 */
1039 private UserInfo getUserInfoNoChecks(int userId) {
1040 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001041 final UserData userData = mUsers.get(userId);
1042 return userData != null ? userData.info : null;
1043 }
1044 }
1045
1046 /**
1047 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1048 * <p>No permissions checking or any addition checks are made</p>
1049 */
1050 private UserData getUserDataNoChecks(int userId) {
1051 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001052 return mUsers.get(userId);
1053 }
1054 }
1055
Amith Yamasani236b2b52015-08-18 14:32:14 -07001056 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001057 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001058 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001059 }
1060
Amith Yamasani258848d2012-08-10 17:06:33 -07001061 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001062 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001063 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001064 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001065 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001066 UserData userData = getUserDataNoChecks(userId);
1067 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001068 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1069 return;
1070 }
Amith Yamasani12747872015-12-07 14:19:49 -08001071 if (name != null && !name.equals(userData.info.name)) {
1072 userData.info.name = name;
1073 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001074 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001075 }
1076 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001077 if (changed) {
1078 sendUserInfoChangedBroadcast(userId);
1079 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001080 }
1081
Amith Yamasani258848d2012-08-10 17:06:33 -07001082 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001083 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001084 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001085 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1086 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1087 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001088 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001089 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001090 }
1091
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001092
1093
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001094 private void sendUserInfoChangedBroadcast(int userId) {
1095 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1096 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1097 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001098 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001099 }
1100
Amith Yamasani258848d2012-08-10 17:06:33 -07001101 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001102 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001103 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001104 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001105 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1106 if (targetUserInfo == null || targetUserInfo.partial) {
1107 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001108 return null;
1109 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001110
1111 final int callingUserId = UserHandle.getCallingUserId();
1112 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1113 final int targetGroupId = targetUserInfo.profileGroupId;
1114 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1115 && callingGroupId == targetGroupId);
1116 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001117 checkManageUsersPermission("get the icon of a user who is not related");
1118 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001119
1120 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001121 return null;
1122 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001123 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001124 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001125
1126 try {
1127 return ParcelFileDescriptor.open(
1128 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1129 } catch (FileNotFoundException e) {
1130 Log.e(LOG_TAG, "Couldn't find icon file", e);
1131 }
1132 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001133 }
1134
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001135 public void makeInitialized(int userId) {
1136 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001137 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001138 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001139 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001140 userData = mUsers.get(userId);
1141 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001142 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001143 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001144 }
Amith Yamasani12747872015-12-07 14:19:49 -08001145 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1146 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001147 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001148 }
1149 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001150 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001151 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001152 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001153 }
1154
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001155 /**
1156 * If default guest restrictions haven't been initialized yet, add the basic
1157 * restrictions.
1158 */
1159 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001160 synchronized (mGuestRestrictions) {
1161 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001162 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001163 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001164 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1165 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1166 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001167 }
1168 }
1169
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001170 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301171 public Bundle getDefaultGuestRestrictions() {
1172 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001173 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301174 return new Bundle(mGuestRestrictions);
1175 }
1176 }
1177
1178 @Override
1179 public void setDefaultGuestRestrictions(Bundle restrictions) {
1180 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001181 synchronized (mGuestRestrictions) {
1182 mGuestRestrictions.clear();
1183 mGuestRestrictions.putAll(restrictions);
1184 }
1185 synchronized (mPackagesLock) {
1186 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301187 }
1188 }
1189
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001190 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001191 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001192 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001193 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1194 boolean isDeviceOwner, int cameraRestrictionScope) {
1195 final Bundle global = new Bundle();
1196 final Bundle local = new Bundle();
1197
1198 // Sort restrictions into local and global ensuring they don't overlap.
1199 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1200 cameraRestrictionScope, global, local);
1201
1202 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001203 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001204 // Update global and local restrictions if they were changed.
1205 globalChanged = updateRestrictionsIfNeededLR(
1206 userId, global, mDevicePolicyGlobalUserRestrictions);
1207 localChanged = updateRestrictionsIfNeededLR(
1208 userId, local, mDevicePolicyLocalUserRestrictions);
1209
1210 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001211 // Remember the global restriction owner userId to be able to make a distinction
1212 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001213 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001214 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001215 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001216 // When profile owner sets restrictions it passes null global bundle and we
1217 // reset global restriction owner userId.
1218 // This means this user used to have DO, but now the DO is gone and the user
1219 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001220 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001221 }
1222 }
1223 }
1224 if (DBG) {
1225 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1226 + " global=" + global + (globalChanged ? " (changed)" : "")
1227 + " local=" + local + (localChanged ? " (changed)" : "")
1228 );
1229 }
1230 // Don't call them within the mRestrictionsLock.
1231 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001232 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001233 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001234 }
1235 }
1236
1237 synchronized (mRestrictionsLock) {
1238 if (globalChanged) {
1239 applyUserRestrictionsForAllUsersLR();
1240 } else if (localChanged) {
1241 applyUserRestrictionsLR(userId);
1242 }
1243 }
1244 }
1245
Pavel Grafov6a40f092016-10-25 15:46:51 +01001246 /**
1247 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1248 * empty, record is removed from the array.
1249 * @return whether restrictions bundle is different from the old one.
1250 */
1251 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1252 SparseArray<Bundle> restrictionsArray) {
1253 final boolean changed =
1254 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1255 if (changed) {
1256 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1257 restrictionsArray.put(userId, restrictions);
1258 } else {
1259 restrictionsArray.delete(userId);
1260 }
1261 }
1262 return changed;
1263 }
1264
Makoto Onuki068c54a2015-10-13 14:34:03 -07001265 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001266 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001267 final Bundle baseRestrictions =
1268 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001269 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001270 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001271
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001272 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1273 // Common case first.
1274 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001275 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001276 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1277 UserRestrictionsUtils.merge(effective, global);
1278 UserRestrictionsUtils.merge(effective, local);
1279
Makoto Onuki068c54a2015-10-13 14:34:03 -07001280 return effective;
1281 }
1282
1283 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001284 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001285 if (DBG) {
1286 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1287 }
1288 mCachedEffectiveUserRestrictions.remove(userId);
1289 }
1290
1291 private Bundle getEffectiveUserRestrictions(int userId) {
1292 synchronized (mRestrictionsLock) {
1293 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1294 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001295 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001296 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1297 }
1298 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001299 }
1300 }
1301
Makoto Onuki068c54a2015-10-13 14:34:03 -07001302 /** @return a specific user restriction that's in effect currently. */
1303 @Override
1304 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001305 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1306 return false;
1307 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001308 Bundle restrictions = getEffectiveUserRestrictions(userId);
1309 return restrictions != null && restrictions.getBoolean(restrictionKey);
1310 }
1311
1312 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001313 * @hide
1314 *
1315 * Returns who set a user restriction on a user.
1316 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1317 * @param restrictionKey the string key representing the restriction
1318 * @param userId the id of the user for whom to retrieve the restrictions.
1319 * @return The source of user restriction. Any combination of
1320 * {@link UserManager#RESTRICTION_NOT_SET},
1321 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1322 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1323 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1324 */
1325 @Override
1326 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001327 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1328 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001329 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001330 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1331 result |= enforcingUsers.get(i).getUserRestrictionSource();
1332 }
1333 return result;
1334 }
1335
1336 @Override
1337 public List<EnforcingUser> getUserRestrictionSources(
1338 String restrictionKey, @UserIdInt int userId) {
1339 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001340
1341 // Shortcut for the most common case
1342 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001343 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001344 }
1345
Pavel Grafov6a40f092016-10-25 15:46:51 +01001346 final List<EnforcingUser> result = new ArrayList<>();
1347
1348 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001349 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001350 result.add(new EnforcingUser(
1351 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001352 }
1353
Pavel Grafov6a40f092016-10-25 15:46:51 +01001354 synchronized (mRestrictionsLock) {
1355 // Check if it is set by profile owner.
1356 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1357 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1358 result.add(getEnforcingUserLocked(userId));
1359 }
1360
1361 // Iterate over all users who enforce global restrictions.
1362 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1363 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1364 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1365 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1366 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001367 }
1368 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001369 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001370 return result;
1371 }
1372
Pavel Grafov6a40f092016-10-25 15:46:51 +01001373 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1374 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1375 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1376 return new EnforcingUser(userId, source);
1377 }
1378
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001379 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001380 * @return UserRestrictions that are in effect currently. This always returns a new
1381 * {@link Bundle}.
1382 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001383 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001384 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001385 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001386 }
1387
1388 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001389 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1390 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001391 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1392 return false;
1393 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001394 synchronized (mRestrictionsLock) {
1395 Bundle bundle = mBaseUserRestrictions.get(userId);
1396 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1397 }
1398 }
1399
1400 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001401 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001402 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001403 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1404 return;
1405 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001406 synchronized (mRestrictionsLock) {
1407 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1408 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001409 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1410 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001411 newRestrictions.putBoolean(key, value);
1412
Fyodor Kupolov82402752015-10-28 14:54:51 -07001413 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001414 }
1415 }
1416
Makoto Onuki068c54a2015-10-13 14:34:03 -07001417 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001418 * Optionally updating user restrictions, calculate the effective user restrictions and also
1419 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001420 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001421 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001422 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001423 * @param userId target user ID.
1424 */
1425 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001426 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001427 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001428 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1429 mAppliedUserRestrictions.get(userId));
1430
1431 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001432 if (newBaseRestrictions != null) {
1433 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001434 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1435
Pavel Grafov6a40f092016-10-25 15:46:51 +01001436 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001437 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001438 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001439
Pavel Grafov6a40f092016-10-25 15:46:51 +01001440 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001441 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001442 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001443 }
1444
Fyodor Kupolov82402752015-10-28 14:54:51 -07001445 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001446
Makoto Onuki759a7632015-10-28 16:43:10 -07001447 mCachedEffectiveUserRestrictions.put(userId, effective);
1448
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001450 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001451 debug("Applying user restrictions: userId=" + userId
1452 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001453 }
1454
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001455 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001456 mHandler.post(new Runnable() {
1457 @Override
1458 public void run() {
1459 try {
1460 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1461 } catch (RemoteException e) {
1462 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1463 }
1464 }
1465 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001466 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001467
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001468 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001469
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001470 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001471 }
1472
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001473 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001474 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001475 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1476 // actually, but we still need some kind of synchronization otherwise we might end up
1477 // calling listeners out-of-order, thus "LR".
1478
1479 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1480 return;
1481 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001482
1483 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1484 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1485
1486 mHandler.post(new Runnable() {
1487 @Override
1488 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001489 UserRestrictionsUtils.applyUserRestrictions(
1490 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001491
Makoto Onukid45a4a22015-11-02 17:17:38 -08001492 final UserRestrictionsListener[] listeners;
1493 synchronized (mUserRestrictionsListeners) {
1494 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1495 mUserRestrictionsListeners.toArray(listeners);
1496 }
1497 for (int i = 0; i < listeners.length; i++) {
1498 listeners[i].onUserRestrictionsChanged(userId,
1499 newRestrictionsFinal, prevRestrictionsFinal);
1500 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001501
1502 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1503 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1504 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001505 }
1506 });
1507 }
1508
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001509 // Package private for the inner class.
1510 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001511 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001512 }
1513
1514 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001515 // Package private for the inner class.
1516 void applyUserRestrictionsForAllUsersLR() {
1517 if (DBG) {
1518 debug("applyUserRestrictionsForAllUsersLR");
1519 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001520 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001521 mCachedEffectiveUserRestrictions.clear();
1522
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001523 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001524 // it on a handler.
1525 final Runnable r = new Runnable() {
1526 @Override
1527 public void run() {
1528 // Then get the list of running users.
1529 final int[] runningUsers;
1530 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001531 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001532 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001533 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001534 return;
1535 }
1536 // Then re-calculate the effective restrictions and apply, only for running users.
1537 // It's okay if a new user has started after the getRunningUserIds() call,
1538 // because we'll do the same thing (re-calculate the restrictions and apply)
1539 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001540 synchronized (mRestrictionsLock) {
1541 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001542 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001543 }
1544 }
1545 }
1546 };
1547 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001548 }
1549
Amith Yamasani258848d2012-08-10 17:06:33 -07001550 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001551 * Check if we've hit the limit of how many users can be created.
1552 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001553 private boolean isUserLimitReached() {
1554 int count;
1555 synchronized (mUsersLock) {
1556 count = getAliveUsersExcludingGuestsCountLU();
1557 }
1558 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001559 }
1560
1561 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001562 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001563 checkManageUsersPermission("check if more managed profiles can be added.");
1564 if (ActivityManager.isLowRamDeviceStatic()) {
1565 return false;
1566 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001567 if (!mContext.getPackageManager().hasSystemFeature(
1568 PackageManager.FEATURE_MANAGED_USERS)) {
1569 return false;
1570 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001571 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001572 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001573 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001574 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001575 return false;
1576 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001577 synchronized(mUsersLock) {
1578 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001579 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001580 return false;
1581 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001582 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1583 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001584 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001585 return usersCountAfterRemoving == 1
1586 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001587 }
1588 }
1589
Fyodor Kupolov82402752015-10-28 14:54:51 -07001590 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001591 int aliveUserCount = 0;
1592 final int totalUserCount = mUsers.size();
1593 // Skip over users being removed
1594 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001595 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001596 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001597 aliveUserCount++;
1598 }
1599 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001600 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001601 }
1602
1603 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001604 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001605 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1606 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1607 * permissions can make certain calls to the UserManager.
1608 *
1609 * @param message used as message if SecurityException is thrown
1610 * @throws SecurityException if the caller does not have enough privilege.
1611 */
1612 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1613 final int uid = Binder.getCallingUid();
1614 if (uid != Process.SYSTEM_UID && uid != 0
1615 && ActivityManager.checkComponentPermission(
1616 Manifest.permission.MANAGE_USERS,
1617 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1618 && ActivityManager.checkComponentPermission(
1619 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1620 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1621 throw new SecurityException(
1622 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1623 + message);
1624 }
1625 }
1626
1627 /**
1628 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001629 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001630 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001631 *
1632 * @param message used as message if SecurityException is thrown
1633 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001634 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001635 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001636 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001637 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001638 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1639 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001640 }
1641
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001642 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001643 * Enforces that only the system UID or root's UID or apps that have the
1644 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1645 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1646 * can make certain calls to the UserManager.
1647 *
1648 * @param message used as message if SecurityException is thrown
1649 * @throws SecurityException if the caller is not system or root
1650 * @see #hasManageOrCreateUsersPermission()
1651 */
1652 private static final void checkManageOrCreateUsersPermission(String message) {
1653 if (!hasManageOrCreateUsersPermission()) {
1654 throw new SecurityException(
1655 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1656 }
1657 }
1658
1659 /**
1660 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1661 * to create user/profiles other than what is allowed for
1662 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1663 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1664 */
1665 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1666 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1667 if (!hasManageOrCreateUsersPermission()) {
1668 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1669 + "permission to create an user with flags: " + creationFlags);
1670 }
1671 } else if (!hasManageUsersPermission()) {
1672 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1673 + " with flags: " + creationFlags);
1674 }
1675 }
1676
1677 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001678 * @return whether the calling UID is system UID or root's UID or the calling app has the
1679 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1680 */
1681 private static final boolean hasManageUsersPermission() {
1682 final int callingUid = Binder.getCallingUid();
1683 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1684 || callingUid == Process.ROOT_UID
1685 || ActivityManager.checkComponentPermission(
1686 android.Manifest.permission.MANAGE_USERS,
1687 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1688 }
1689
1690 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001691 * @return whether the calling UID is system UID or root's UID or the calling app has the
1692 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1693 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1694 */
1695 private static final boolean hasManageOrCreateUsersPermission() {
1696 final int callingUid = Binder.getCallingUid();
1697 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1698 || callingUid == Process.ROOT_UID
1699 || ActivityManager.checkComponentPermission(
1700 android.Manifest.permission.MANAGE_USERS,
1701 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1702 || ActivityManager.checkComponentPermission(
1703 android.Manifest.permission.CREATE_USERS,
1704 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1705 }
1706
1707 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001708 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1709 * UserManager.
1710 *
1711 * @param message used as message if SecurityException is thrown
1712 * @throws SecurityException if the caller is not system or root
1713 */
1714 private static void checkSystemOrRoot(String message) {
1715 final int uid = Binder.getCallingUid();
1716 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1717 throw new SecurityException("Only system may: " + message);
1718 }
1719 }
1720
Fyodor Kupolov82402752015-10-28 14:54:51 -07001721 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001722 try {
1723 File dir = new File(mUsersDir, Integer.toString(info.id));
1724 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001725 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001726 if (!dir.exists()) {
1727 dir.mkdir();
1728 FileUtils.setPermissions(
1729 dir.getPath(),
1730 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1731 -1, -1);
1732 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001733 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001734 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001735 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001736 info.iconPath = file.getAbsolutePath();
1737 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001738 try {
1739 os.close();
1740 } catch (IOException ioe) {
1741 // What the ... !
1742 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001743 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001744 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001745 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001746 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001747 }
1748
Amith Yamasani0b285492011-04-14 17:35:23 -07001749 /**
1750 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1751 * cache it elsewhere.
1752 * @return the array of user ids.
1753 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001754 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001755 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001756 return mUserIds;
1757 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001758 }
1759
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001760 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001761 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001762 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001763 return;
1764 }
1765 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001766 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001767 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001768 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001769 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001770 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001771 int type;
1772 while ((type = parser.next()) != XmlPullParser.START_TAG
1773 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001774 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001775 }
1776
1777 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001778 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001779 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001780 return;
1781 }
1782
Amith Yamasani2a003292012-08-14 18:25:45 -07001783 mNextSerialNumber = -1;
1784 if (parser.getName().equals(TAG_USERS)) {
1785 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1786 if (lastSerialNumber != null) {
1787 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1788 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001789 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1790 if (versionNumber != null) {
1791 mUserVersion = Integer.parseInt(versionNumber);
1792 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001793 }
1794
Pavel Grafov6a40f092016-10-25 15:46:51 +01001795 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1796 // currently), take care of it in case of upgrade.
1797 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001798
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001799 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301800 if (type == XmlPullParser.START_TAG) {
1801 final String name = parser.getName();
1802 if (name.equals(TAG_USER)) {
1803 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001804
Amith Yamasani12747872015-12-07 14:19:49 -08001805 UserData userData = readUserLP(Integer.parseInt(id));
1806
1807 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001808 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001809 mUsers.put(userData.info.id, userData);
1810 if (mNextSerialNumber < 0
1811 || mNextSerialNumber <= userData.info.id) {
1812 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001813 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301814 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001815 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301816 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001817 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1818 && type != XmlPullParser.END_TAG) {
1819 if (type == XmlPullParser.START_TAG) {
1820 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001821 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07001822 UserRestrictionsUtils
1823 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001824 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001825 }
1826 break;
1827 }
1828 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001829 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1830 // Legacy name, should only be encountered when upgrading from pre-O.
1831 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001832 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1833 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001834 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001835 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001836 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1837 // Should only happen when upgrading from pre-O (version < 7).
1838 oldDevicePolicyGlobalUserRestrictions =
1839 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001840 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001841 }
1842 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001843
Fyodor Kupolov82402752015-10-28 14:54:51 -07001844 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001845 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001846 } catch (IOException | XmlPullParserException e) {
1847 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001848 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001849 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001850 }
1851 }
1852
Amith Yamasani6f34b412012-10-22 18:19:27 -07001853 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001854 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001855 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001856 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001857 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001858 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001859 int userVersion = mUserVersion;
1860 if (userVersion < 1) {
1861 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001862 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1863 if ("Primary".equals(userData.info.name)) {
1864 userData.info.name =
1865 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1866 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001867 }
1868 userVersion = 1;
1869 }
1870
Amith Yamasanibc9625052012-11-15 14:39:18 -08001871 if (userVersion < 2) {
1872 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001873 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1874 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1875 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1876 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001877 }
1878 userVersion = 2;
1879 }
1880
Amith Yamasani350962c2013-08-06 11:18:53 -07001881
Amith Yamasani5e486f52013-08-07 11:06:44 -07001882 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001883 userVersion = 4;
1884 }
1885
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001886 if (userVersion < 5) {
1887 initDefaultGuestRestrictions();
1888 userVersion = 5;
1889 }
1890
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001891 if (userVersion < 6) {
1892 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001893 synchronized (mUsersLock) {
1894 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001895 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001896 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001897 if (!splitSystemUser && userData.info.isRestricted()
1898 && (userData.info.restrictedProfileParentId
1899 == UserInfo.NO_PROFILE_GROUP_ID)) {
1900 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1901 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001902 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001903 }
1904 }
1905 userVersion = 6;
1906 }
1907
Pavel Grafov6a40f092016-10-25 15:46:51 +01001908 if (userVersion < 7) {
1909 // Previously only one user could enforce global restrictions, now it is per-user.
1910 synchronized (mRestrictionsLock) {
1911 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
1912 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
1913 mDevicePolicyGlobalUserRestrictions.put(
1914 mDeviceOwnerUserId, oldGlobalUserRestrictions);
1915 }
1916 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
1917 // it from local to global bundle for all users who set it.
1918 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
1919 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
1920 );
1921 }
1922 userVersion = 7;
1923 }
1924
Amith Yamasani6f34b412012-10-22 18:19:27 -07001925 if (userVersion < USER_VERSION) {
1926 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1927 + USER_VERSION);
1928 } else {
1929 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001930
1931 if (originalVersion < mUserVersion) {
1932 writeUserListLP();
1933 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001934 }
1935 }
1936
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001937 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001938 int flags = UserInfo.FLAG_INITIALIZED;
1939 // In split system user mode, the admin and primary flags are assigned to the first human
1940 // user.
1941 if (!UserManager.isSplitSystemUser()) {
1942 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1943 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001944 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001945 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001946 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001947 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001948 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001949
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001950 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001951 try {
1952 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1953 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1954 for (String userRestriction : defaultFirstUserRestrictions) {
1955 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1956 restrictions.putBoolean(userRestriction, true);
1957 }
1958 }
1959 } catch (Resources.NotFoundException e) {
1960 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1961 }
1962
Pavel Grafov6a40f092016-10-25 15:46:51 +01001963 if (!restrictions.isEmpty()) {
1964 synchronized (mRestrictionsLock) {
1965 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1966 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001967 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001968
Fyodor Kupolov82402752015-10-28 14:54:51 -07001969 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001970 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001971
Amith Yamasani12747872015-12-07 14:19:49 -08001972 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001973 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001974 }
1975
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001976 private String getOwnerName() {
1977 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1978 }
1979
Amith Yamasani12747872015-12-07 14:19:49 -08001980 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001981 if (DBG) {
1982 debug("scheduleWriteUser");
1983 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001984 // No need to wrap it within a lock -- worst case, we'll just post the same message
1985 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001986 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1987 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001988 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1989 }
1990 }
1991
Amith Yamasani12747872015-12-07 14:19:49 -08001992 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001993 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001994 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001995 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001996 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001997 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001998 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001999 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002000 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002001 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002002 userFile.finishWrite(fos);
2003 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002004 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002005 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002006 }
2007 }
2008
2009 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002010 * Writes the user file in this format:
2011 *
2012 * <user flags="20039023" id="0">
2013 * <name>Primary</name>
2014 * </user>
2015 */
2016 @VisibleForTesting
2017 void writeUserLP(UserData userData, OutputStream os)
2018 throws IOException, XmlPullParserException {
2019 // XmlSerializer serializer = XmlUtils.serializerInstance();
2020 final XmlSerializer serializer = new FastXmlSerializer();
2021 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2022 serializer.startDocument(null, true);
2023 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2024
2025 final UserInfo userInfo = userData.info;
2026 serializer.startTag(null, TAG_USER);
2027 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2028 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2029 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2030 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2031 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2032 Long.toString(userInfo.lastLoggedInTime));
2033 if (userInfo.lastLoggedInFingerprint != null) {
2034 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2035 userInfo.lastLoggedInFingerprint);
2036 }
2037 if (userInfo.iconPath != null) {
2038 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2039 }
2040 if (userInfo.partial) {
2041 serializer.attribute(null, ATTR_PARTIAL, "true");
2042 }
2043 if (userInfo.guestToRemove) {
2044 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2045 }
2046 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2047 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2048 Integer.toString(userInfo.profileGroupId));
2049 }
2050 serializer.attribute(null, ATTR_PROFILE_BADGE,
2051 Integer.toString(userInfo.profileBadge));
2052 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2053 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2054 Integer.toString(userInfo.restrictedProfileParentId));
2055 }
2056 // Write seed data
2057 if (userData.persistSeedData) {
2058 if (userData.seedAccountName != null) {
2059 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2060 }
2061 if (userData.seedAccountType != null) {
2062 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2063 }
2064 }
2065 if (userInfo.name != null) {
2066 serializer.startTag(null, TAG_NAME);
2067 serializer.text(userInfo.name);
2068 serializer.endTag(null, TAG_NAME);
2069 }
2070 synchronized (mRestrictionsLock) {
2071 UserRestrictionsUtils.writeRestrictions(serializer,
2072 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2073 UserRestrictionsUtils.writeRestrictions(serializer,
2074 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2075 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002076 UserRestrictionsUtils.writeRestrictions(serializer,
2077 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2078 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002079 }
2080
2081 if (userData.account != null) {
2082 serializer.startTag(null, TAG_ACCOUNT);
2083 serializer.text(userData.account);
2084 serializer.endTag(null, TAG_ACCOUNT);
2085 }
2086
2087 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2088 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2089 userData.seedAccountOptions.saveToXml(serializer);
2090 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2091 }
2092
2093 serializer.endTag(null, TAG_USER);
2094
2095 serializer.endDocument();
2096 }
2097
2098 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002099 * Writes the user list file in this format:
2100 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002101 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002102 * <user id="0"></user>
2103 * <user id="2"></user>
2104 * </users>
2105 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002106 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002107 if (DBG) {
2108 debug("writeUserList");
2109 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002110 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002111 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002112 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002113 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002114 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2115
2116 // XmlSerializer serializer = XmlUtils.serializerInstance();
2117 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002118 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002119 serializer.startDocument(null, true);
2120 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2121
2122 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002123 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002124 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002125
Adam Lesinskieddeb492014-09-08 17:50:03 -07002126 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002127 synchronized (mGuestRestrictions) {
2128 UserRestrictionsUtils
2129 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2130 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302131 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002132 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2133 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2134 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002135 int[] userIdsToWrite;
2136 synchronized (mUsersLock) {
2137 userIdsToWrite = new int[mUsers.size()];
2138 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002139 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002140 userIdsToWrite[i] = user.id;
2141 }
2142 }
2143 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002144 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002145 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002146 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002147 }
2148
2149 serializer.endTag(null, TAG_USERS);
2150
2151 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002152 userListFile.finishWrite(fos);
2153 } catch (Exception e) {
2154 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002155 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002156 }
2157 }
2158
Amith Yamasani12747872015-12-07 14:19:49 -08002159 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002160 FileInputStream fis = null;
2161 try {
2162 AtomicFile userFile =
2163 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2164 fis = userFile.openRead();
2165 return readUserLP(id, fis);
2166 } catch (IOException ioe) {
2167 Slog.e(LOG_TAG, "Error reading user list");
2168 } catch (XmlPullParserException pe) {
2169 Slog.e(LOG_TAG, "Error reading user list");
2170 } finally {
2171 IoUtils.closeQuietly(fis);
2172 }
2173 return null;
2174 }
2175
2176 @VisibleForTesting
2177 UserData readUserLP(int id, InputStream is) throws IOException,
2178 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002179 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002180 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002181 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002182 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002183 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002184 long creationTime = 0L;
2185 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002186 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002187 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002188 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002189 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002190 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002191 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002192 boolean persistSeedData = false;
2193 String seedAccountName = null;
2194 String seedAccountType = null;
2195 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002196 Bundle baseRestrictions = null;
2197 Bundle localRestrictions = null;
2198 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002199
Kenny Guy02c89902016-11-15 19:36:38 +00002200 XmlPullParser parser = Xml.newPullParser();
2201 parser.setInput(is, StandardCharsets.UTF_8.name());
2202 int type;
2203 while ((type = parser.next()) != XmlPullParser.START_TAG
2204 && type != XmlPullParser.END_DOCUMENT) {
2205 // Skip
2206 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002207
Kenny Guy02c89902016-11-15 19:36:38 +00002208 if (type != XmlPullParser.START_TAG) {
2209 Slog.e(LOG_TAG, "Unable to read user " + id);
2210 return null;
2211 }
2212
2213 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2214 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2215 if (storedId != id) {
2216 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002217 return null;
2218 }
Kenny Guy02c89902016-11-15 19:36:38 +00002219 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2220 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2221 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2222 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2223 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2224 lastLoggedInFingerprint = parser.getAttributeValue(null,
2225 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2226 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2227 UserInfo.NO_PROFILE_GROUP_ID);
2228 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2229 restrictedProfileParentId = readIntAttribute(parser,
2230 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2231 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2232 if ("true".equals(valueString)) {
2233 partial = true;
2234 }
2235 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2236 if ("true".equals(valueString)) {
2237 guestToRemove = true;
2238 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002239
Kenny Guy02c89902016-11-15 19:36:38 +00002240 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2241 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2242 if (seedAccountName != null || seedAccountType != null) {
2243 persistSeedData = true;
2244 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002245
Kenny Guy02c89902016-11-15 19:36:38 +00002246 int outerDepth = parser.getDepth();
2247 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2248 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2249 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2250 continue;
2251 }
2252 String tag = parser.getName();
2253 if (TAG_NAME.equals(tag)) {
2254 type = parser.next();
2255 if (type == XmlPullParser.TEXT) {
2256 name = parser.getText();
2257 }
2258 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002259 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002260 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002261 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2262 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2263 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002264 } else if (TAG_ACCOUNT.equals(tag)) {
2265 type = parser.next();
2266 if (type == XmlPullParser.TEXT) {
2267 account = parser.getText();
2268 }
2269 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2270 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002271 persistSeedData = true;
2272 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002273 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002274 }
Kenny Guy02c89902016-11-15 19:36:38 +00002275
2276 // Create the UserInfo object that gets passed around
2277 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2278 userInfo.serialNumber = serialNumber;
2279 userInfo.creationTime = creationTime;
2280 userInfo.lastLoggedInTime = lastLoggedInTime;
2281 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2282 userInfo.partial = partial;
2283 userInfo.guestToRemove = guestToRemove;
2284 userInfo.profileGroupId = profileGroupId;
2285 userInfo.profileBadge = profileBadge;
2286 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2287
2288 // Create the UserData object that's internal to this class
2289 UserData userData = new UserData();
2290 userData.info = userInfo;
2291 userData.account = account;
2292 userData.seedAccountName = seedAccountName;
2293 userData.seedAccountType = seedAccountType;
2294 userData.persistSeedData = persistSeedData;
2295 userData.seedAccountOptions = seedAccountOptions;
2296
2297 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002298 if (baseRestrictions != null) {
2299 mBaseUserRestrictions.put(id, baseRestrictions);
2300 }
2301 if (localRestrictions != null) {
2302 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2303 }
2304 if (globalRestrictions != null) {
2305 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2306 }
Kenny Guy02c89902016-11-15 19:36:38 +00002307 }
2308 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002309 }
2310
Amith Yamasani920ace02012-09-20 22:15:37 -07002311 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2312 String valueString = parser.getAttributeValue(null, attr);
2313 if (valueString == null) return defaultValue;
2314 try {
2315 return Integer.parseInt(valueString);
2316 } catch (NumberFormatException nfe) {
2317 return defaultValue;
2318 }
2319 }
2320
2321 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2322 String valueString = parser.getAttributeValue(null, attr);
2323 if (valueString == null) return defaultValue;
2324 try {
2325 return Long.parseLong(valueString);
2326 } catch (NumberFormatException nfe) {
2327 return defaultValue;
2328 }
2329 }
2330
Amith Yamasanib82add22013-07-09 11:24:44 -07002331 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002332 * Removes the app restrictions file for a specific package and user id, if it exists.
2333 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002334 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2335 File dir = Environment.getUserSystemDirectory(userId);
2336 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2337 if (resFile.exists()) {
2338 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002339 }
2340 }
2341
Kenny Guya52dc3e2014-02-11 15:33:14 +00002342 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002343 public UserInfo createProfileForUser(String name, int flags, int userId,
2344 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002345 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002346 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002347 }
2348
Amith Yamasani258848d2012-08-10 17:06:33 -07002349 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002350 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2351 String[] disallowedPackages) {
2352 checkManageOrCreateUsersPermission(flags);
2353 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2354 }
2355
2356 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002357 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2358 checkManageOrCreateUsersPermission("Only the system can remove users");
2359 return removeUserUnchecked(userHandle);
2360 }
2361
2362 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002363 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002364 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002365 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002366 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002367
Jessica Hummelbe81c802014-04-22 15:49:22 +01002368 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002369 return createUserInternal(name, flags, parentId, null);
2370 }
2371
2372 private UserInfo createUserInternal(String name, int flags, int parentId,
2373 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002374 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2375 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2376 : UserManager.DISALLOW_ADD_USER;
2377 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2378 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002379 return null;
2380 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002381 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2382 }
2383
2384 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2385 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002386 DeviceStorageMonitorInternal dsm = LocalServices
2387 .getService(DeviceStorageMonitorInternal.class);
2388 if (dsm.isMemoryLow()) {
2389 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2390 return null;
2391 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002392 if (ActivityManager.isLowRamDeviceStatic()) {
2393 return null;
2394 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002395 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002396 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002397 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002398 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002399 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002400 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002401 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002402 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002403 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002404 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002405 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002406 if (parentId != UserHandle.USER_NULL) {
2407 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002408 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002409 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002410 if (parent == null) return null;
2411 }
2412 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2413 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2414 return null;
2415 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002416 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2417 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002418 // been reached, cannot add a user.
2419 return null;
2420 }
2421 // If we're adding a guest and there already exists one, bail.
2422 if (isGuest && findCurrentGuestUser() != null) {
2423 return null;
2424 }
2425 // In legacy mode, restricted profile's parent can only be the owner user
2426 if (isRestricted && !UserManager.isSplitSystemUser()
2427 && (parentId != UserHandle.USER_SYSTEM)) {
2428 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2429 return null;
2430 }
2431 if (isRestricted && UserManager.isSplitSystemUser()) {
2432 if (parent == null) {
2433 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2434 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002435 return null;
2436 }
Amith Yamasani12747872015-12-07 14:19:49 -08002437 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002438 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2439 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002440 return null;
2441 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002442 }
2443 // In split system user mode, we assign the first human user the primary flag.
2444 // And if there is no device owner, we also assign the admin flag to primary user.
2445 if (UserManager.isSplitSystemUser()
2446 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2447 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002448 synchronized (mUsersLock) {
2449 if (!mIsDeviceManaged) {
2450 flags |= UserInfo.FLAG_ADMIN;
2451 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002452 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002453 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002454
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002455 userId = getNextAvailableId();
2456 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002457 boolean ephemeralGuests = Resources.getSystem()
2458 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002459
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002460 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002461 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2462 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2463 || (parent != null && parent.info.isEphemeral())) {
2464 flags |= UserInfo.FLAG_EPHEMERAL;
2465 }
2466
2467 userInfo = new UserInfo(userId, name, null, flags);
2468 userInfo.serialNumber = mNextSerialNumber++;
2469 long now = System.currentTimeMillis();
2470 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2471 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002472 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002473 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2474 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2475 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002476 userData = new UserData();
2477 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002478 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002479 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002480 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002481 writeUserListLP();
2482 if (parent != null) {
2483 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002484 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2485 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002486 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002487 }
Amith Yamasani12747872015-12-07 14:19:49 -08002488 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002489 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002490 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2491 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002492 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002493 }
Amith Yamasani12747872015-12-07 14:19:49 -08002494 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002495 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002496 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002497 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002498 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002499 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002500 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002501 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002502 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002503 userInfo.partial = false;
2504 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002505 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002506 }
2507 updateUserIds();
2508 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002509 if (isGuest) {
2510 synchronized (mGuestRestrictions) {
2511 restrictions.putAll(mGuestRestrictions);
2512 }
2513 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002514 synchronized (mRestrictionsLock) {
2515 mBaseUserRestrictions.append(userId, restrictions);
2516 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002517 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002518 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2519 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2520 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2521 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002522 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2523 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002524 } finally {
2525 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002526 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002527 return userInfo;
2528 }
2529
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002530 @VisibleForTesting
2531 UserData putUserInfo(UserInfo userInfo) {
2532 final UserData userData = new UserData();
2533 userData.info = userInfo;
2534 synchronized (mUsers) {
2535 mUsers.put(userInfo.id, userData);
2536 }
2537 return userData;
2538 }
2539
2540 @VisibleForTesting
2541 void removeUserInfo(int userId) {
2542 synchronized (mUsers) {
2543 mUsers.remove(userId);
2544 }
2545 }
2546
Amith Yamasani0b285492011-04-14 17:35:23 -07002547 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002548 * @hide
2549 */
Amith Yamasani12747872015-12-07 14:19:49 -08002550 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002551 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002552 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002553 final UserInfo user = createProfileForUser(
2554 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002555 if (user == null) {
2556 return null;
2557 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002558 long identity = Binder.clearCallingIdentity();
2559 try {
2560 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2561 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2562 // the putIntForUser() will fail.
2563 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2564 android.provider.Settings.Secure.LOCATION_MODE,
2565 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2566 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2567 } finally {
2568 Binder.restoreCallingIdentity(identity);
2569 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002570 return user;
2571 }
2572
2573 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002574 * Find the current guest user. If the Guest user is partial,
2575 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002576 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002577 private UserInfo findCurrentGuestUser() {
2578 synchronized (mUsersLock) {
2579 final int size = mUsers.size();
2580 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002581 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002582 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2583 return user;
2584 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002585 }
2586 }
2587 return null;
2588 }
2589
2590 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002591 * Mark this guest user for deletion to allow us to create another guest
2592 * and switch to that user before actually removing this guest.
2593 * @param userHandle the userid of the current guest
2594 * @return whether the user could be marked for deletion
2595 */
Amith Yamasani12747872015-12-07 14:19:49 -08002596 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002597 public boolean markGuestForDeletion(int userHandle) {
2598 checkManageUsersPermission("Only the system can remove users");
2599 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2600 UserManager.DISALLOW_REMOVE_USER, false)) {
2601 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2602 return false;
2603 }
2604
2605 long ident = Binder.clearCallingIdentity();
2606 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002607 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002608 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002609 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002610 userData = mUsers.get(userHandle);
2611 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002612 return false;
2613 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002614 }
Amith Yamasani12747872015-12-07 14:19:49 -08002615 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002616 return false;
2617 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002618 // We set this to a guest user that is to be removed. This is a temporary state
2619 // where we are allowed to add new Guest users, even if this one is still not
2620 // removed. This user will still show up in getUserInfo() calls.
2621 // If we don't get around to removing this Guest user, it will be purged on next
2622 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002623 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002624 // Mark it as disabled, so that it isn't returned any more when
2625 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002626 userData.info.flags |= UserInfo.FLAG_DISABLED;
2627 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002628 }
2629 } finally {
2630 Binder.restoreCallingIdentity(ident);
2631 }
2632 return true;
2633 }
2634
2635 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002636 * Removes a user and all data directories created for that user. This method should be called
2637 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002638 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002639 */
Amith Yamasani12747872015-12-07 14:19:49 -08002640 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002641 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002642 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002643 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002644
2645 final boolean isManagedProfile;
2646 synchronized (mUsersLock) {
2647 UserInfo userInfo = getUserInfoLU(userHandle);
2648 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2649 }
2650 String restriction = isManagedProfile
2651 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2652 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2653 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002654 return false;
2655 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002656 return removeUserUnchecked(userHandle);
2657 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002658
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002659 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002660 long ident = Binder.clearCallingIdentity();
2661 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002662 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002663 int currentUser = ActivityManager.getCurrentUser();
2664 if (currentUser == userHandle) {
2665 Log.w(LOG_TAG, "Current user cannot be removed");
2666 return false;
2667 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002668 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002669 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002670 userData = mUsers.get(userHandle);
2671 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002672 return false;
2673 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002674
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002675 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002676 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002677
Kenny Guyee58b4f2014-05-23 15:19:53 +01002678 // Set this to a partially created user, so that the user will be purged
2679 // on next startup, in case the runtime stops now before stopping and
2680 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002681 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002682 // Mark it as disabled, so that it isn't returned any more when
2683 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002684 userData.info.flags |= UserInfo.FLAG_DISABLED;
2685 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002686 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002687 try {
2688 mAppOpsService.removeUser(userHandle);
2689 } catch (RemoteException e) {
2690 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2691 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002692
Amith Yamasani12747872015-12-07 14:19:49 -08002693 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2694 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002695 // Send broadcast to notify system that the user removed was a
2696 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002697 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002698 }
2699
2700 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2701 int res;
2702 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002703 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002704 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002705 @Override
2706 public void userStopped(int userId) {
2707 finishRemoveUser(userId);
2708 }
2709 @Override
2710 public void userStopAborted(int userId) {
2711 }
2712 });
2713 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002714 return false;
2715 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002716 return res == ActivityManager.USER_OP_SUCCESS;
2717 } finally {
2718 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002719 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002720 }
2721
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002722 @VisibleForTesting
2723 void addRemovingUserIdLocked(int userId) {
2724 // We remember deleted user IDs to prevent them from being
2725 // reused during the current boot; they can still be reused
2726 // after a reboot or recycling of userIds.
2727 mRemovingUserIds.put(userId, true);
2728 mRecentlyRemovedIds.add(userId);
2729 // Keep LRU queue of recently removed IDs for recycling
2730 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2731 mRecentlyRemovedIds.removeFirst();
2732 }
2733 }
2734
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002735 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002736 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002737 // Let other services shutdown any activity and clean up their state before completely
2738 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002739 long ident = Binder.clearCallingIdentity();
2740 try {
2741 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2742 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002743 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2744 android.Manifest.permission.MANAGE_USERS,
2745
2746 new BroadcastReceiver() {
2747 @Override
2748 public void onReceive(Context context, Intent intent) {
2749 if (DBG) {
2750 Slog.i(LOG_TAG,
2751 "USER_REMOVED broadcast sent, cleaning up user data "
2752 + userHandle);
2753 }
2754 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002755 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002756 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002757 // Clean up any ActivityManager state
2758 LocalServices.getService(ActivityManagerInternal.class)
2759 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002760 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002761 }
2762 }.start();
2763 }
2764 },
2765
2766 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002767 } finally {
2768 Binder.restoreCallingIdentity(ident);
2769 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002770 }
2771
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002772 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002773 try {
2774 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2775 } catch (IllegalStateException e) {
2776 // This may be simply because the user was partially created.
2777 Slog.i(LOG_TAG,
2778 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2779 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002780
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002781 // Cleanup gatekeeper secure user id
2782 try {
2783 final IGateKeeperService gk = GateKeeper.getService();
2784 if (gk != null) {
2785 gk.clearSecureUserId(userHandle);
2786 }
2787 } catch (Exception ex) {
2788 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2789 }
2790
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002791 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002792 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002793
2794 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002795 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002796 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2797
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002798 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002799 synchronized (mUsersLock) {
2800 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002801 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002802 }
2803 synchronized (mUserStates) {
2804 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002805 }
2806 synchronized (mRestrictionsLock) {
2807 mBaseUserRestrictions.remove(userHandle);
2808 mAppliedUserRestrictions.remove(userHandle);
2809 mCachedEffectiveUserRestrictions.remove(userHandle);
2810 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002811 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2812 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2813 applyUserRestrictionsForAllUsersLR();
2814 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002815 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002816 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002817 synchronized (mPackagesLock) {
2818 writeUserListLP();
2819 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002820 // Remove user file
2821 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2822 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002823 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002824 if (RELEASE_DELETED_USER_ID) {
2825 synchronized (mUsers) {
2826 mRemovingUserIds.delete(userHandle);
2827 }
2828 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002829 }
2830
Kenny Guyf8d3a232014-05-15 16:09:52 +01002831 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002832 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002833 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2834 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002835 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002836 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002837 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002838 }
2839
Amith Yamasani2a003292012-08-14 18:25:45 -07002840 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002841 public Bundle getApplicationRestrictions(String packageName) {
2842 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2843 }
2844
2845 @Override
2846 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002847 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002848 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002849 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002850 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002851 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002852 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002853 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002854 }
2855 }
2856
2857 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002858 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002859 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002860 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002861 if (restrictions != null) {
2862 restrictions.setDefusable(true);
2863 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002864 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002865 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002866 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002867 } else {
2868 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002869 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002870 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002871 }
Robin Lee66e5d962014-04-09 16:44:21 +01002872
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002873 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2874 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2875 changeIntent.setPackage(packageName);
2876 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2877 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002878 }
2879
2880 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002881 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002882 try {
2883 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002884 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002885 } catch (NameNotFoundException nnfe) {
2886 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002887 } finally {
2888 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002889 }
2890 }
2891
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002892 @GuardedBy("mAppRestrictionsLock")
2893 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002894 AtomicFile restrictionsFile =
2895 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2896 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002897 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002898 }
2899
2900 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002901 @GuardedBy("mAppRestrictionsLock")
2902 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002903 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002904 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002905 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002906 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002907 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002908
2909 FileInputStream fis = null;
2910 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002911 fis = restrictionsFile.openRead();
2912 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002913 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002914 XmlUtils.nextElement(parser);
2915 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002916 Slog.e(LOG_TAG, "Unable to read restrictions file "
2917 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002918 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002919 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002920 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2921 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002922 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002923 } catch (IOException|XmlPullParserException e) {
2924 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002925 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002926 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002927 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002928 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002929 }
2930
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002931 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2932 XmlPullParser parser) throws XmlPullParserException, IOException {
2933 int type = parser.getEventType();
2934 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2935 String key = parser.getAttributeValue(null, ATTR_KEY);
2936 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2937 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2938 if (multiple != null) {
2939 values.clear();
2940 int count = Integer.parseInt(multiple);
2941 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2942 if (type == XmlPullParser.START_TAG
2943 && parser.getName().equals(TAG_VALUE)) {
2944 values.add(parser.nextText().trim());
2945 count--;
2946 }
2947 }
2948 String [] valueStrings = new String[values.size()];
2949 values.toArray(valueStrings);
2950 restrictions.putStringArray(key, valueStrings);
2951 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2952 restrictions.putBundle(key, readBundleEntry(parser, values));
2953 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2954 final int outerDepth = parser.getDepth();
2955 ArrayList<Bundle> bundleList = new ArrayList<>();
2956 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2957 Bundle childBundle = readBundleEntry(parser, values);
2958 bundleList.add(childBundle);
2959 }
2960 restrictions.putParcelableArray(key,
2961 bundleList.toArray(new Bundle[bundleList.size()]));
2962 } else {
2963 String value = parser.nextText().trim();
2964 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2965 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2966 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2967 restrictions.putInt(key, Integer.parseInt(value));
2968 } else {
2969 restrictions.putString(key, value);
2970 }
2971 }
2972 }
2973 }
2974
2975 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2976 throws IOException, XmlPullParserException {
2977 Bundle childBundle = new Bundle();
2978 final int outerDepth = parser.getDepth();
2979 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2980 readEntry(childBundle, values, parser);
2981 }
2982 return childBundle;
2983 }
2984
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002985 @GuardedBy("mAppRestrictionsLock")
2986 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002987 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002988 AtomicFile restrictionsFile = new AtomicFile(
2989 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002990 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002991 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002992 }
2993
2994 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002995 @GuardedBy("mAppRestrictionsLock")
2996 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002997 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002998 try {
2999 fos = restrictionsFile.startWrite();
3000 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3001
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003002 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003003 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003004 serializer.startDocument(null, true);
3005 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3006
3007 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003008 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003009 serializer.endTag(null, TAG_RESTRICTIONS);
3010
3011 serializer.endDocument();
3012 restrictionsFile.finishWrite(fos);
3013 } catch (Exception e) {
3014 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003015 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3016 }
3017 }
3018
3019 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3020 throws IOException {
3021 for (String key : restrictions.keySet()) {
3022 Object value = restrictions.get(key);
3023 serializer.startTag(null, TAG_ENTRY);
3024 serializer.attribute(null, ATTR_KEY, key);
3025
3026 if (value instanceof Boolean) {
3027 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3028 serializer.text(value.toString());
3029 } else if (value instanceof Integer) {
3030 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3031 serializer.text(value.toString());
3032 } else if (value == null || value instanceof String) {
3033 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3034 serializer.text(value != null ? (String) value : "");
3035 } else if (value instanceof Bundle) {
3036 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3037 writeBundle((Bundle) value, serializer);
3038 } else if (value instanceof Parcelable[]) {
3039 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3040 Parcelable[] array = (Parcelable[]) value;
3041 for (Parcelable parcelable : array) {
3042 if (!(parcelable instanceof Bundle)) {
3043 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3044 }
3045 serializer.startTag(null, TAG_ENTRY);
3046 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3047 writeBundle((Bundle) parcelable, serializer);
3048 serializer.endTag(null, TAG_ENTRY);
3049 }
3050 } else {
3051 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3052 String[] values = (String[]) value;
3053 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3054 for (String choice : values) {
3055 serializer.startTag(null, TAG_VALUE);
3056 serializer.text(choice != null ? choice : "");
3057 serializer.endTag(null, TAG_VALUE);
3058 }
3059 }
3060 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003061 }
3062 }
3063
3064 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003065 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003066 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003067 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003068 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003069 }
3070 }
3071
3072 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003073 public boolean isUserNameSet(int userHandle) {
3074 synchronized (mUsersLock) {
3075 UserInfo userInfo = getUserInfoLU(userHandle);
3076 return userInfo != null && userInfo.name != null;
3077 }
3078 }
3079
3080 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003081 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003082 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003083 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003084 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003085 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003086 }
3087 // Not found
3088 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003089 }
3090 }
3091
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003092 @Override
3093 public long getUserCreationTime(int userHandle) {
3094 int callingUserId = UserHandle.getCallingUserId();
3095 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003096 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003097 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003098 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003099 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003100 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003101 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003102 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003103 }
3104 }
3105 }
3106 if (userInfo == null) {
3107 throw new SecurityException("userHandle can only be the calling user or a managed "
3108 + "profile associated with this user");
3109 }
3110 return userInfo.creationTime;
3111 }
3112
Amith Yamasani0b285492011-04-14 17:35:23 -07003113 /**
3114 * Caches the list of user ids in an array, adjusting the array size when necessary.
3115 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003116 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003117 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003118 synchronized (mUsersLock) {
3119 final int userSize = mUsers.size();
3120 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003121 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003122 num++;
3123 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003124 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003125 final int[] newUsers = new int[num];
3126 int n = 0;
3127 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003128 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003129 newUsers[n++] = mUsers.keyAt(i);
3130 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003131 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003132 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003133 }
3134 }
3135
3136 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003137 * Called right before a user is started. This gives us a chance to prepare
3138 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003139 */
3140 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003141 UserInfo userInfo = getUserInfo(userId);
3142 if (userInfo == null) {
3143 return;
3144 }
3145 final int userSerial = userInfo.serialNumber;
3146 // Migrate only if build fingerprints mismatch
3147 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003148 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003149 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003150
3151 if (userId != UserHandle.USER_SYSTEM) {
3152 synchronized (mRestrictionsLock) {
3153 applyUserRestrictionsLR(userId);
3154 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003155 }
3156 }
3157
3158 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003159 * Called right before a user is unlocked. This gives us a chance to prepare
3160 * app storage.
3161 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003162 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003163 UserInfo userInfo = getUserInfo(userId);
3164 if (userInfo == null) {
3165 return;
3166 }
3167 final int userSerial = userInfo.serialNumber;
3168 // Migrate only if build fingerprints mismatch
3169 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003170 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003171 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003172 }
3173
3174 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003175 * Examine all users present on given mounted volume, and destroy data
3176 * belonging to users that are no longer valid, or whose user ID has been
3177 * recycled.
3178 */
3179 void reconcileUsers(String volumeUuid) {
3180 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3181 }
3182
3183 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003184 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003185 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003186 * @param userId the user that was just foregrounded
3187 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003188 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003189 UserData userData = getUserDataNoChecks(userId);
3190 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003191 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3192 return;
3193 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003194
3195 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003196 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003197 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003198 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003199 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3200 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003201 }
3202
3203 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003204 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003205 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003206 @VisibleForTesting
3207 int getNextAvailableId() {
3208 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003209 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003210 nextId = scanNextAvailableIdLocked();
3211 if (nextId >= 0) {
3212 return nextId;
3213 }
3214 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3215 // except most recently removed
3216 if (mRemovingUserIds.size() > 0) {
3217 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3218 mRemovingUserIds.clear();
3219 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3220 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003221 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003222 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003223 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003224 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003225 if (nextId < 0) {
3226 throw new IllegalStateException("No user id available!");
3227 }
3228 return nextId;
3229 }
3230
3231 private int scanNextAvailableIdLocked() {
3232 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3233 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3234 return i;
3235 }
3236 }
3237 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003238 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003239
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003240 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003241 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3242 }
3243
Amith Yamasani920ace02012-09-20 22:15:37 -07003244 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003245 public void setSeedAccountData(int userId, String accountName, String accountType,
3246 PersistableBundle accountOptions, boolean persist) {
3247 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3248 synchronized (mPackagesLock) {
3249 final UserData userData;
3250 synchronized (mUsersLock) {
3251 userData = getUserDataLU(userId);
3252 if (userData == null) {
3253 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3254 return;
3255 }
3256 userData.seedAccountName = accountName;
3257 userData.seedAccountType = accountType;
3258 userData.seedAccountOptions = accountOptions;
3259 userData.persistSeedData = persist;
3260 }
3261 if (persist) {
3262 writeUserLP(userData);
3263 }
3264 }
3265 }
3266
3267 @Override
3268 public String getSeedAccountName() throws RemoteException {
3269 checkManageUsersPermission("Cannot get seed account information");
3270 synchronized (mUsersLock) {
3271 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3272 return userData.seedAccountName;
3273 }
3274 }
3275
3276 @Override
3277 public String getSeedAccountType() throws RemoteException {
3278 checkManageUsersPermission("Cannot get seed account information");
3279 synchronized (mUsersLock) {
3280 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3281 return userData.seedAccountType;
3282 }
3283 }
3284
3285 @Override
3286 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3287 checkManageUsersPermission("Cannot get seed account information");
3288 synchronized (mUsersLock) {
3289 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3290 return userData.seedAccountOptions;
3291 }
3292 }
3293
3294 @Override
3295 public void clearSeedAccountData() throws RemoteException {
3296 checkManageUsersPermission("Cannot clear seed account information");
3297 synchronized (mPackagesLock) {
3298 UserData userData;
3299 synchronized (mUsersLock) {
3300 userData = getUserDataLU(UserHandle.getCallingUserId());
3301 if (userData == null) return;
3302 userData.clearSeedAccountData();
3303 }
3304 writeUserLP(userData);
3305 }
3306 }
3307
3308 @Override
3309 public boolean someUserHasSeedAccount(String accountName, String accountType)
3310 throws RemoteException {
3311 checkManageUsersPermission("Cannot check seed account information");
3312 synchronized (mUsersLock) {
3313 final int userSize = mUsers.size();
3314 for (int i = 0; i < userSize; i++) {
3315 final UserData data = mUsers.valueAt(i);
3316 if (data.info.isInitialized()) continue;
3317 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3318 continue;
3319 }
3320 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3321 continue;
3322 }
3323 return true;
3324 }
3325 }
3326 return false;
3327 }
3328
3329 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003330 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003331 FileDescriptor err, String[] args, ShellCallback callback,
3332 ResultReceiver resultReceiver) {
3333 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003334 }
3335
3336 int onShellCommand(Shell shell, String cmd) {
3337 if (cmd == null) {
3338 return shell.handleDefaultCommands(cmd);
3339 }
3340
3341 final PrintWriter pw = shell.getOutPrintWriter();
3342 try {
3343 switch(cmd) {
3344 case "list":
3345 return runList(pw);
3346 }
3347 } catch (RemoteException e) {
3348 pw.println("Remote exception: " + e);
3349 }
3350 return -1;
3351 }
3352
3353 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003354 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003355 final List<UserInfo> users = getUsers(false);
3356 if (users == null) {
3357 pw.println("Error: couldn't get users");
3358 return 1;
3359 } else {
3360 pw.println("Users:");
3361 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003362 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003363 pw.println("\t" + users.get(i).toString() + running);
3364 }
3365 return 0;
3366 }
3367 }
3368
3369 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003370 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003371 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003372
3373 long now = System.currentTimeMillis();
3374 StringBuilder sb = new StringBuilder();
3375 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003376 synchronized (mUsersLock) {
3377 pw.println("Users:");
3378 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003379 UserData userData = mUsers.valueAt(i);
3380 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003381 continue;
3382 }
Amith Yamasani12747872015-12-07 14:19:49 -08003383 UserInfo userInfo = userData.info;
3384 final int userId = userInfo.id;
3385 pw.print(" "); pw.print(userInfo);
3386 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003387 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003388 pw.print(" <removing> ");
3389 }
Amith Yamasani12747872015-12-07 14:19:49 -08003390 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003391 pw.print(" <partial>");
3392 }
3393 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003394 pw.print(" State: ");
3395 final int state;
3396 synchronized (mUserStates) {
3397 state = mUserStates.get(userId, -1);
3398 }
3399 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003400 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003401 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003402 pw.println("<unknown>");
3403 } else {
3404 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003405 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003406 sb.append(" ago");
3407 pw.println(sb);
3408 }
3409 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003410 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003411 pw.println("<unknown>");
3412 } else {
3413 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003414 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003415 sb.append(" ago");
3416 pw.println(sb);
3417 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003418 pw.print(" Last logged in fingerprint: ");
3419 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003420 pw.print(" Has profile owner: ");
3421 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003422 pw.println(" Restrictions:");
3423 synchronized (mRestrictionsLock) {
3424 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003425 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003426 pw.println(" Device policy global restrictions:");
3427 UserRestrictionsUtils.dumpRestrictions(
3428 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003429 pw.println(" Device policy local restrictions:");
3430 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003431 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003432 pw.println(" Effective restrictions:");
3433 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003434 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003435 }
Amith Yamasani12747872015-12-07 14:19:49 -08003436
3437 if (userData.account != null) {
3438 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003439 pw.println();
3440 }
Amith Yamasani12747872015-12-07 14:19:49 -08003441
3442 if (userData.seedAccountName != null) {
3443 pw.print(" Seed account name: " + userData.seedAccountName);
3444 pw.println();
3445 if (userData.seedAccountType != null) {
3446 pw.print(" account type: " + userData.seedAccountType);
3447 pw.println();
3448 }
3449 if (userData.seedAccountOptions != null) {
3450 pw.print(" account options exist");
3451 pw.println();
3452 }
3453 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003454 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003455 }
Amith Yamasani12747872015-12-07 14:19:49 -08003456 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003457 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003458 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003459 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003460 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003461 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003462 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003463 synchronized (mUsersLock) {
3464 pw.println();
3465 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003466 if (mRemovingUserIds.size() > 0) {
3467 pw.println();
3468 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3469 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003470 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003471 synchronized (mUserStates) {
3472 pw.println(" Started users state: " + mUserStates);
3473 }
Amith Yamasani12747872015-12-07 14:19:49 -08003474 // Dump some capabilities
3475 pw.println();
3476 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3477 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003478 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3479 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003480 }
3481 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003482
3483 final class MainHandler extends Handler {
3484
3485 @Override
3486 public void handleMessage(Message msg) {
3487 switch (msg.what) {
3488 case WRITE_USER_MSG:
3489 removeMessages(WRITE_USER_MSG, msg.obj);
3490 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003491 int userId = ((UserData) msg.obj).info.id;
3492 UserData userData = getUserDataNoChecks(userId);
3493 if (userData != null) {
3494 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003495 }
3496 }
3497 }
3498 }
3499 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003500
3501 /**
3502 * @param userId
3503 * @return whether the user has been initialized yet
3504 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003505 boolean isUserInitialized(int userId) {
3506 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003507 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003508
3509 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003510 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003511 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3512 boolean isDeviceOwner, int cameraRestrictionScope) {
3513 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3514 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003515 }
3516
3517 @Override
3518 public Bundle getBaseUserRestrictions(int userId) {
3519 synchronized (mRestrictionsLock) {
3520 return mBaseUserRestrictions.get(userId);
3521 }
3522 }
3523
3524 @Override
3525 public void setBaseUserRestrictionsByDpmsForMigration(
3526 int userId, Bundle baseRestrictions) {
3527 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003528 if (updateRestrictionsIfNeededLR(
3529 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3530 invalidateEffectiveUserRestrictionsLR(userId);
3531 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003532 }
3533
Amith Yamasani12747872015-12-07 14:19:49 -08003534 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003535 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003536 if (userData != null) {
3537 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003538 } else {
3539 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3540 }
3541 }
3542 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003543
3544 @Override
3545 public boolean getUserRestriction(int userId, String key) {
3546 return getUserRestrictions(userId).getBoolean(key);
3547 }
3548
3549 @Override
3550 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3551 synchronized (mUserRestrictionsListeners) {
3552 mUserRestrictionsListeners.add(listener);
3553 }
3554 }
3555
3556 @Override
3557 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3558 synchronized (mUserRestrictionsListeners) {
3559 mUserRestrictionsListeners.remove(listener);
3560 }
3561 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003562
3563 @Override
3564 public void setDeviceManaged(boolean isManaged) {
3565 synchronized (mUsersLock) {
3566 mIsDeviceManaged = isManaged;
3567 }
3568 }
3569
3570 @Override
3571 public void setUserManaged(int userId, boolean isManaged) {
3572 synchronized (mUsersLock) {
3573 mIsUserManaged.put(userId, isManaged);
3574 }
3575 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003576
3577 @Override
3578 public void setUserIcon(int userId, Bitmap bitmap) {
3579 long ident = Binder.clearCallingIdentity();
3580 try {
3581 synchronized (mPackagesLock) {
3582 UserData userData = getUserDataNoChecks(userId);
3583 if (userData == null || userData.info.partial) {
3584 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3585 return;
3586 }
3587 writeBitmapLP(userData.info, bitmap);
3588 writeUserLP(userData);
3589 }
3590 sendUserInfoChangedBroadcast(userId);
3591 } finally {
3592 Binder.restoreCallingIdentity(ident);
3593 }
3594 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003595
3596 @Override
3597 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3598 synchronized (mUsersLock) {
3599 mForceEphemeralUsers = forceEphemeralUsers;
3600 }
3601 }
3602
3603 @Override
3604 public void removeAllUsers() {
3605 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3606 // Remove the non-system users straight away.
3607 removeNonSystemUsers();
3608 } else {
3609 // Switch to the system user first and then remove the other users.
3610 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3611 @Override
3612 public void onReceive(Context context, Intent intent) {
3613 int userId =
3614 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3615 if (userId != UserHandle.USER_SYSTEM) {
3616 return;
3617 }
3618 mContext.unregisterReceiver(this);
3619 removeNonSystemUsers();
3620 }
3621 };
3622 IntentFilter userSwitchedFilter = new IntentFilter();
3623 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3624 mContext.registerReceiver(
3625 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3626
3627 // Switch to the system user.
3628 ActivityManager am =
3629 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3630 am.switchUser(UserHandle.USER_SYSTEM);
3631 }
3632 }
phweisse9c44062016-02-10 12:57:38 +01003633
3634 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003635 public void onEphemeralUserStop(int userId) {
3636 synchronized (mUsersLock) {
3637 UserInfo userInfo = getUserInfoLU(userId);
3638 if (userInfo != null && userInfo.isEphemeral()) {
3639 // Do not allow switching back to the ephemeral user again as the user is going
3640 // to be deleted.
3641 userInfo.flags |= UserInfo.FLAG_DISABLED;
3642 if (userInfo.isGuest()) {
3643 // Indicate that the guest will be deleted after it stops.
3644 userInfo.guestToRemove = true;
3645 }
3646 }
3647 }
3648 }
3649
3650 @Override
phweisse9c44062016-02-10 12:57:38 +01003651 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003652 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003653 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003654 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003655 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3656 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3657 }
3658 return user;
3659 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003660
3661 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003662 public boolean removeUserEvenWhenDisallowed(int userId) {
3663 return removeUserUnchecked(userId);
3664 }
3665
3666 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003667 public boolean isUserRunning(int userId) {
3668 synchronized (mUserStates) {
3669 return mUserStates.get(userId, -1) >= 0;
3670 }
3671 }
3672
3673 @Override
3674 public void setUserState(int userId, int userState) {
3675 synchronized (mUserStates) {
3676 mUserStates.put(userId, userState);
3677 }
3678 }
3679
3680 @Override
3681 public void removeUserState(int userId) {
3682 synchronized (mUserStates) {
3683 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003684 }
3685 }
3686
3687 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003688 public int[] getUserIds() {
3689 return UserManagerService.this.getUserIds();
3690 }
3691
3692 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003693 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003694 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003695 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003696 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003697 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003698 // Special case, in the stopping/shutdown state user key can still be unlocked
3699 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3700 return StorageManager.isUserKeyUnlocked(userId);
3701 }
3702 return (state == UserState.STATE_RUNNING_UNLOCKING)
3703 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003704 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003705
3706 @Override
3707 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003708 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003709 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003710 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003711 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003712 // Special case, in the stopping/shutdown state user key can still be unlocked
3713 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3714 return StorageManager.isUserKeyUnlocked(userId);
3715 }
3716 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003717 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07003718
3719 @Override
3720 public boolean isUserInitialized(int userId) {
3721 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3722 }
3723
3724 @Override
3725 public boolean exists(int userId) {
3726 return getUserInfoNoChecks(userId) != null;
3727 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003728 }
3729
3730 /* Remove all the users except of the system one. */
3731 private void removeNonSystemUsers() {
3732 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3733 synchronized (mUsersLock) {
3734 final int userSize = mUsers.size();
3735 for (int i = 0; i < userSize; i++) {
3736 UserInfo ui = mUsers.valueAt(i).info;
3737 if (ui.id != UserHandle.USER_SYSTEM) {
3738 usersToRemove.add(ui);
3739 }
3740 }
3741 }
3742 for (UserInfo ui: usersToRemove) {
3743 removeUser(ui.id);
3744 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003745 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003746
3747 private class Shell extends ShellCommand {
3748 @Override
3749 public int onCommand(String cmd) {
3750 return onShellCommand(this, cmd);
3751 }
3752
3753 @Override
3754 public void onHelp() {
3755 final PrintWriter pw = getOutPrintWriter();
3756 pw.println("User manager (user) commands:");
3757 pw.println(" help");
3758 pw.println(" Print this help text.");
3759 pw.println("");
3760 pw.println(" list");
3761 pw.println(" Prints all users on the system.");
3762 }
3763 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003764
3765 private static void debug(String message) {
3766 Log.d(LOG_TAG, message +
3767 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3768 }
Kenny Guy02c89902016-11-15 19:36:38 +00003769
3770 @VisibleForTesting
3771 static int getMaxManagedProfiles() {
3772 // Allow overriding max managed profiles on debuggable builds for testing
3773 // of multiple profiles.
3774 if (!Build.IS_DEBUGGABLE) {
3775 return MAX_MANAGED_PROFILES;
3776 } else {
3777 return SystemProperties.getInt("persist.sys.max_profiles",
3778 MAX_MANAGED_PROFILES);
3779 }
3780 }
3781
3782 @VisibleForTesting
3783 int getFreeProfileBadgeLU(int parentUserId) {
3784 int maxManagedProfiles = getMaxManagedProfiles();
3785 boolean[] usedBadges = new boolean[maxManagedProfiles];
3786 final int userSize = mUsers.size();
3787 for (int i = 0; i < userSize; i++) {
3788 UserInfo ui = mUsers.valueAt(i).info;
3789 // Check which badge indexes are already used by this profile group.
3790 if (ui.isManagedProfile()
3791 && ui.profileGroupId == parentUserId
3792 && !mRemovingUserIds.get(ui.id)
3793 && ui.profileBadge < maxManagedProfiles) {
3794 usedBadges[ui.profileBadge] = true;
3795 }
3796 }
3797 for (int i = 0; i < maxManagedProfiles; i++) {
3798 if (!usedBadges[i]) {
3799 return i;
3800 }
3801 }
3802 return 0;
3803 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003804
3805 /**
3806 * Checks if the given user has a managed profile associated with it.
3807 * @param userId The parent user
3808 * @return
3809 */
3810 boolean hasManagedProfile(int userId) {
3811 synchronized (mUsersLock) {
3812 UserInfo userInfo = getUserInfoLU(userId);
3813 final int userSize = mUsers.size();
3814 for (int i = 0; i < userSize; i++) {
3815 UserInfo profile = mUsers.valueAt(i).info;
3816 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3817 return true;
3818 }
3819 }
3820 return false;
3821 }
3822 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003823}