blob: 8206bdab255db742dacd74248620e275539e303c [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chenb3b92582015-12-07 11:22:13 -080019import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070021import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070022import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070023import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070024import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070026import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010031import android.content.IntentFilter;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070032import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070033import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080034import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070035import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010036import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070037import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070038import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080039import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080040import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070041import android.os.Environment;
42import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080043import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080044import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080046import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010047import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070048import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080049import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070050import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070051import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070052import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010053import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040054import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070055import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070056import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070057import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070058import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080059import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010060import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070061import android.os.storage.VolumeInfo;
62import android.system.ErrnoException;
63import android.system.Os;
64import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070065import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070066import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import android.util.Slog;
68import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080069import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070070import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070071import android.util.Xml;
72
Makoto Onuki068c54a2015-10-13 14:34:03 -070073import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070074import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040075import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080076import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080077import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070078import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070079import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000080import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070081import com.android.server.LocalServices;
Jeff Sharkey47f71082016-02-01 17:03:54 -070082
83import libcore.io.IoUtils;
84import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080085
86import org.xmlpull.v1.XmlPullParser;
87import org.xmlpull.v1.XmlPullParserException;
88import org.xmlpull.v1.XmlSerializer;
89
Amith Yamasani4b2e9342011-03-31 12:38:53 -070090import java.io.BufferedOutputStream;
91import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070092import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070094import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095import java.io.FileOutputStream;
96import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070097import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010098import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099import java.util.ArrayList;
100import java.util.List;
101
Makoto Onuki068c54a2015-10-13 14:34:03 -0700102/**
103 * Service for {@link UserManager}.
104 *
105 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700106 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800107 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700108 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
109 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
110 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700111 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700112public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700113 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800114 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800115 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700116
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800118 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700120 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700122 private static final String ATTR_CREATION_TIME = "created";
123 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700124 private static final String ATTR_SERIAL_NO = "serialNumber";
125 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700126 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700127 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700128 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100129 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700130 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800131 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
132 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530133 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700135 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800136 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800137 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800138 private static final String TAG_ENTRY = "entry";
139 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800140 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800141 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700142 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800143 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700145 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
146 private static final String ATTR_TYPE_STRING = "s";
147 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700148 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700149 private static final String ATTR_TYPE_BUNDLE = "B";
150 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700151
Amith Yamasani0b285492011-04-14 17:35:23 -0700152 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700153 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700154 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100155 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700156
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800157 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700158 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800159
Amith Yamasani634cf312012-10-04 17:34:21 -0700160 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700161 // We need to keep process uid within Integer.MAX_VALUE.
162 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700163
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700164 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700165
Amith Yamasani920ace02012-09-20 22:15:37 -0700166 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
167
Nicolas Prevotb8186812015-08-06 15:00:03 +0100168 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700169 // without first making sure that the rest of the framework is prepared for it.
170 private static final int MAX_MANAGED_PROFILES = 1;
171
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800172 static final int WRITE_USER_MSG = 1;
173 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530174
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700175 private static final String XATTR_SERIAL = "user.serial";
176
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800177 // Tron counters
178 private static final String TRON_GUEST_CREATED = "users_guest_created";
179 private static final String TRON_USER_CREATED = "users_user_created";
180
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 private final Context mContext;
182 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700183 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700184 // Short-term lock for internal state, when interaction/sync with PM is not required
185 private final Object mUsersLock = new Object();
186 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700187
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800188 private final Handler mHandler;
189
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190 private final File mUsersDir;
191 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700192
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800193 private static final IBinder mUserRestriconToken = new Binder();
194
Makoto Onuki068c54a2015-10-13 14:34:03 -0700195 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800196 * User-related information that is used for persisting to flash. Only UserInfo is
197 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800198 */
Amith Yamasani12747872015-12-07 14:19:49 -0800199 private static class UserData {
200 // Basic user information and properties
201 UserInfo info;
202 // Account name used when there is a strong association between a user and an account
203 String account;
204 // Account information for seeding into a newly created user. This could also be
205 // used for login validation for an existing user, for updating their credentials.
206 // In the latter case, data may not need to be persisted as it is only valid for the
207 // current login session.
208 String seedAccountName;
209 String seedAccountType;
210 PersistableBundle seedAccountOptions;
211 // Whether to perist the seed account information to be available after a boot
212 boolean persistSeedData;
213
214 void clearSeedAccountData() {
215 seedAccountName = null;
216 seedAccountType = null;
217 seedAccountOptions = null;
218 persistSeedData = false;
219 }
220 }
221
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800222 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800223 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800224
225 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700226 * User restrictions set via UserManager. This doesn't include restrictions set by
227 * device owner / profile owners.
228 *
229 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
230 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
231 * maybe shared between {@link #mBaseUserRestrictions} and
232 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
233 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700234 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700235 */
236 @GuardedBy("mRestrictionsLock")
237 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
238
239 /**
240 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
241 * with device / profile owner restrictions. We'll initialize it lazily; use
242 * {@link #getEffectiveUserRestrictions} to access it.
243 *
244 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
245 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
246 * maybe shared between {@link #mBaseUserRestrictions} and
247 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
248 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700249 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700250 */
251 @GuardedBy("mRestrictionsLock")
252 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
253
Makoto Onuki4f160732015-10-27 17:15:38 -0700254 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800255 * User restrictions that have already been applied in
256 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
257 * that have changed since the last
258 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700259 */
260 @GuardedBy("mRestrictionsLock")
261 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
262
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800263 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800264 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
265 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800266 */
267 @GuardedBy("mRestrictionsLock")
268 private Bundle mDevicePolicyGlobalUserRestrictions;
269
270 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800271 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
272 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800273 */
274 @GuardedBy("mRestrictionsLock")
275 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
276
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800277 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530278 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800279
280 /**
281 * Set of user IDs being actively removed. Removed IDs linger in this set
282 * for several seconds to work around a VFS caching issue.
283 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700284 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800285 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700286
Fyodor Kupolov82402752015-10-28 14:54:51 -0700287 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700288 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800289 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700290 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700291 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700292
Jason Monk62062992014-05-06 09:55:28 -0400293 private IAppOpsService mAppOpsService;
294
Makoto Onuki068c54a2015-10-13 14:34:03 -0700295 private final LocalService mLocalService;
296
Makoto Onukie7927da2015-11-25 10:05:17 -0800297 @GuardedBy("mUsersLock")
298 private boolean mIsDeviceManaged;
299
300 @GuardedBy("mUsersLock")
301 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
302
Makoto Onukid45a4a22015-11-02 17:17:38 -0800303 @GuardedBy("mUserRestrictionsListeners")
304 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
305 new ArrayList<>();
306
Clara Bayarria1771112015-12-18 16:29:18 +0000307 private final LockPatternUtils mLockPatternUtils;
308
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100309 /**
310 * Whether all users should be created ephemeral.
311 */
312 @GuardedBy("mUsersLock")
313 private boolean mForceEphemeralUsers;
314
Amith Yamasani258848d2012-08-10 17:06:33 -0700315 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700316
Dianne Hackborn4428e172012-08-24 17:43:05 -0700317 public static UserManagerService getInstance() {
318 synchronized (UserManagerService.class) {
319 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700320 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700321 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700322
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800323 @VisibleForTesting
324 UserManagerService(File dataDir) {
325 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700326 }
327
Dianne Hackborn4428e172012-08-24 17:43:05 -0700328 /**
329 * Called by package manager to create the service. This is closely
330 * associated with the package manager, and the given lock is the
331 * package manager's own lock.
332 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800333 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
334 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700335 }
336
Dianne Hackborn4428e172012-08-24 17:43:05 -0700337 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800338 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700339 mContext = context;
340 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700341 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800342 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800343 synchronized (mPackagesLock) {
344 mUsersDir = new File(dataDir, USER_INFO_DIR);
345 mUsersDir.mkdirs();
346 // Make zeroth user directory, for services to migrate their files to that location
347 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
348 userZeroDir.mkdirs();
349 FileUtils.setPermissions(mUsersDir.toString(),
350 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
351 -1, -1);
352 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
353 initDefaultGuestRestrictions();
354 readUserListLP();
355 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700356 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700357 mLocalService = new LocalService();
358 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000359 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700360 }
361
362 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100363 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800364 ArrayList<UserInfo> partials = new ArrayList<>();
365 synchronized (mUsersLock) {
366 final int userSize = mUsers.size();
367 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800368 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100369 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800370 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700371 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700372 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700373 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800374 final int partialsSize = partials.size();
375 for (int i = 0; i < partialsSize; i++) {
376 UserInfo ui = partials.get(i);
377 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
378 + " (name=" + ui.name + ")");
379 removeUserState(ui.id);
380 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800381
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700382 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800383
Jason Monk62062992014-05-06 09:55:28 -0400384 mAppOpsService = IAppOpsService.Stub.asInterface(
385 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800386
387 synchronized (mRestrictionsLock) {
388 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400389 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700390 }
391
392 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800393 public String getUserAccount(int userId) {
394 checkManageUserAndAcrossUsersFullPermission("get user account");
395 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800396 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800397 }
398 }
399
400 @Override
401 public void setUserAccount(int userId, String accountName) {
402 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800403 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800404 synchronized (mPackagesLock) {
405 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800406 final UserData userData = mUsers.get(userId);
407 if (userData == null) {
408 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
409 return;
410 }
411 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800412 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800413 userData.account = accountName;
414 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800415 }
416 }
417
418 if (userToUpdate != null) {
419 writeUserLP(userToUpdate);
420 }
421 }
422 }
423
424 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700425 public UserInfo getPrimaryUser() {
426 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700427 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700428 final int userSize = mUsers.size();
429 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800430 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800431 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700432 return ui;
433 }
434 }
435 }
436 return null;
437 }
438
439 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700440 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700441 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700442 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700443 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700444 final int userSize = mUsers.size();
445 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800446 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700447 if (ui.partial) {
448 continue;
449 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800450 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700451 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700452 }
Amith Yamasani13593602012-03-22 16:16:17 -0700453 }
454 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700455 }
Amith Yamasani13593602012-03-22 16:16:17 -0700456 }
457
Amith Yamasani258848d2012-08-10 17:06:33 -0700458 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100459 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800460 if (userId != UserHandle.getCallingUserId()) {
461 checkManageUsersPermission("getting profiles related to user " + userId);
462 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700463 final long ident = Binder.clearCallingIdentity();
464 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700465 synchronized (mUsersLock) {
466 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100467 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700468 } finally {
469 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000470 }
471 }
472
Amith Yamasanibe465322014-04-24 13:45:17 -0700473 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700474 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
475 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700476 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700477 if (user == null) {
478 // Probably a dying user
479 return users;
480 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700481 final int userSize = mUsers.size();
482 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800483 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700484 if (!isProfileOf(user, profile)) {
485 continue;
486 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100487 if (enabledOnly && !profile.isEnabled()) {
488 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700489 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700490 if (mRemovingUserIds.get(profile.id)) {
491 continue;
492 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700493 users.add(profile);
494 }
495 return users;
496 }
497
Jessica Hummelbe81c802014-04-22 15:49:22 +0100498 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700499 public int getCredentialOwnerProfile(int userHandle) {
500 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000501 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700502 synchronized (mUsersLock) {
503 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700504 if (profileParent != null) {
505 return profileParent.id;
506 }
507 }
508 }
509
510 return userHandle;
511 }
512
513 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700514 public boolean isSameProfileGroup(int userId, int otherUserId) {
515 if (userId == otherUserId) return true;
516 checkManageUsersPermission("check if in the same profile group");
517 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700518 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700519 }
520 }
521
Fyodor Kupolov82402752015-10-28 14:54:51 -0700522 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
523 synchronized (mUsersLock) {
524 UserInfo userInfo = getUserInfoLU(userId);
525 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
526 return false;
527 }
528 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
529 if (otherUserInfo == null
530 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
531 return false;
532 }
533 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700534 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700535 }
536
537 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100538 public UserInfo getProfileParent(int userHandle) {
539 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700540 synchronized (mUsersLock) {
541 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700542 }
543 }
544
Fyodor Kupolov82402752015-10-28 14:54:51 -0700545 private UserInfo getProfileParentLU(int userHandle) {
546 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700547 if (profile == null) {
548 return null;
549 }
550 int parentUserId = profile.profileGroupId;
551 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
552 return null;
553 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700554 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100555 }
556 }
557
Fyodor Kupolov82402752015-10-28 14:54:51 -0700558 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100559 return user.id == profile.id ||
560 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
561 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000562 }
563
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000564 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000565 UserHandle parentHandle, boolean inQuietMode) {
566 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
567 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
568 intent.putExtra(Intent.EXTRA_USER, profileHandle);
569 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000570 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000571 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000572 }
573
574 @Override
575 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
576 checkManageUsersPermission("silence profile");
577 boolean changed = false;
578 UserInfo profile, parent;
579 synchronized (mPackagesLock) {
580 synchronized (mUsersLock) {
581 profile = getUserInfoLU(userHandle);
582 parent = getProfileParentLU(userHandle);
583
584 }
585 if (profile == null || !profile.isManagedProfile()) {
586 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
587 }
588 if (profile.isQuietModeEnabled() != enableQuietMode) {
589 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800590 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000591 changed = true;
592 }
593 }
594 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000595 long identity = Binder.clearCallingIdentity();
596 try {
597 if (enableQuietMode) {
598 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
599 } else {
600 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
601 }
602 } catch (RemoteException e) {
603 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
604 } finally {
605 Binder.restoreCallingIdentity(identity);
606 }
607
608 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
609 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000610 }
611 }
612
613 @Override
614 public boolean isQuietModeEnabled(int userHandle) {
615 synchronized (mPackagesLock) {
616 UserInfo info;
617 synchronized (mUsersLock) {
618 info = getUserInfoLU(userHandle);
619 }
620 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000621 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000622 }
623 return info.isQuietModeEnabled();
624 }
625 }
626
Kenny Guya52dc3e2014-02-11 15:33:14 +0000627 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100628 public void setUserEnabled(int userId) {
629 checkManageUsersPermission("enable user");
630 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700631 UserInfo info;
632 synchronized (mUsersLock) {
633 info = getUserInfoLU(userId);
634 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100635 if (info != null && !info.isEnabled()) {
636 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800637 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100638 }
639 }
640 }
641
642 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700643 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700644 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700645 synchronized (mUsersLock) {
646 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700647 }
648 }
649
Amith Yamasani71e6c692013-03-24 17:39:28 -0700650 @Override
651 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700652 synchronized (mUsersLock) {
653 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700654 }
655 }
656
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700657 @Override
658 public boolean canHaveRestrictedProfile(int userId) {
659 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700660 synchronized (mUsersLock) {
661 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700662 if (userInfo == null || !userInfo.canHaveProfile()) {
663 return false;
664 }
665 if (!userInfo.isAdmin()) {
666 return false;
667 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800668 // restricted profile can be created if there is no DO set and the admin user has no PO;
669 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700670 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700671 }
672
Amith Yamasani195263742012-08-21 15:40:12 -0700673 /*
674 * Should be locked on mUsers before calling this.
675 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700676 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800677 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700678 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800679 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700680 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
681 return null;
682 }
Amith Yamasani12747872015-12-07 14:19:49 -0800683 return userData != null ? userData.info : null;
684 }
685
686 private UserData getUserDataLU(int userId) {
687 final UserData userData = mUsers.get(userId);
688 // If it is partial and not in the process of being removed, return as unknown user.
689 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
690 return null;
691 }
692 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700693 }
694
Fyodor Kupolov82402752015-10-28 14:54:51 -0700695 /**
696 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
697 * <p>No permissions checking or any addition checks are made</p>
698 */
699 private UserInfo getUserInfoNoChecks(int userId) {
700 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800701 final UserData userData = mUsers.get(userId);
702 return userData != null ? userData.info : null;
703 }
704 }
705
706 /**
707 * Obtains {@link #mUsersLock} and return UserData from mUsers.
708 * <p>No permissions checking or any addition checks are made</p>
709 */
710 private UserData getUserDataNoChecks(int userId) {
711 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700712 return mUsers.get(userId);
713 }
714 }
715
Amith Yamasani236b2b52015-08-18 14:32:14 -0700716 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700717 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700718 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700719 }
720
Amith Yamasani258848d2012-08-10 17:06:33 -0700721 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700722 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700723 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700724 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700725 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800726 UserData userData = getUserDataNoChecks(userId);
727 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700728 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
729 return;
730 }
Amith Yamasani12747872015-12-07 14:19:49 -0800731 if (name != null && !name.equals(userData.info.name)) {
732 userData.info.name = name;
733 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700734 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700735 }
736 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700737 if (changed) {
738 sendUserInfoChangedBroadcast(userId);
739 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700740 }
741
Amith Yamasani258848d2012-08-10 17:06:33 -0700742 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700743 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700744 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100745 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
746 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
747 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700748 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100749 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700750 }
751
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100752
753
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700754 private void sendUserInfoChangedBroadcast(int userId) {
755 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
756 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
757 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700758 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700759 }
760
Amith Yamasani258848d2012-08-10 17:06:33 -0700761 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100762 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100763 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700764 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100765 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
766 if (targetUserInfo == null || targetUserInfo.partial) {
767 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700768 return null;
769 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100770
771 final int callingUserId = UserHandle.getCallingUserId();
772 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
773 final int targetGroupId = targetUserInfo.profileGroupId;
774 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
775 && callingGroupId == targetGroupId);
776 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100777 checkManageUsersPermission("get the icon of a user who is not related");
778 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100779
780 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700781 return null;
782 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100783 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700784 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100785
786 try {
787 return ParcelFileDescriptor.open(
788 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
789 } catch (FileNotFoundException e) {
790 Log.e(LOG_TAG, "Couldn't find icon file", e);
791 }
792 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700793 }
794
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700795 public void makeInitialized(int userId) {
796 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800797 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800798 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800799 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800800 userData = mUsers.get(userId);
801 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700802 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800803 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700804 }
Amith Yamasani12747872015-12-07 14:19:49 -0800805 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
806 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800807 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700808 }
809 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800810 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800811 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800812 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700813 }
814
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700815 /**
816 * If default guest restrictions haven't been initialized yet, add the basic
817 * restrictions.
818 */
819 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800820 synchronized (mGuestRestrictions) {
821 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800822 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800823 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
824 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
825 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700826 }
827 }
828
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800829 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530830 public Bundle getDefaultGuestRestrictions() {
831 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800832 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530833 return new Bundle(mGuestRestrictions);
834 }
835 }
836
837 @Override
838 public void setDefaultGuestRestrictions(Bundle restrictions) {
839 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800840 synchronized (mGuestRestrictions) {
841 mGuestRestrictions.clear();
842 mGuestRestrictions.putAll(restrictions);
843 }
844 synchronized (mPackagesLock) {
845 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530846 }
847 }
848
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800849 /**
850 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
851 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800852 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800853 @Nullable Bundle global) {
854 Preconditions.checkNotNull(local);
855 boolean globalChanged = false;
856 boolean localChanged;
857 synchronized (mRestrictionsLock) {
858 if (global != null) {
859 // Update global.
860 globalChanged = !UserRestrictionsUtils.areEqual(
861 mDevicePolicyGlobalUserRestrictions, global);
862 if (globalChanged) {
863 mDevicePolicyGlobalUserRestrictions = global;
864 }
865 }
866 {
867 // Update local.
868 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
869 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
870 if (localChanged) {
871 mDevicePolicyLocalUserRestrictions.put(userId, local);
872 }
873 }
874 }
875 if (DBG) {
876 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
877 + " global=" + global + (globalChanged ? " (changed)" : "")
878 + " local=" + local + (localChanged ? " (changed)" : "")
879 );
880 }
881 // Don't call them within the mRestrictionsLock.
882 synchronized (mPackagesLock) {
883 if (globalChanged) {
884 writeUserListLP();
885 }
886 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800887 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800888 }
889 }
890
891 synchronized (mRestrictionsLock) {
892 if (globalChanged) {
893 applyUserRestrictionsForAllUsersLR();
894 } else if (localChanged) {
895 applyUserRestrictionsLR(userId);
896 }
897 }
898 }
899
Makoto Onuki068c54a2015-10-13 14:34:03 -0700900 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700901 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800902 final Bundle baseRestrictions =
903 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
904 final Bundle global = mDevicePolicyGlobalUserRestrictions;
905 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700906
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800907 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
908 // Common case first.
909 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700910 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800911 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
912 UserRestrictionsUtils.merge(effective, global);
913 UserRestrictionsUtils.merge(effective, local);
914
Makoto Onuki068c54a2015-10-13 14:34:03 -0700915 return effective;
916 }
917
918 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700919 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700920 if (DBG) {
921 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
922 }
923 mCachedEffectiveUserRestrictions.remove(userId);
924 }
925
926 private Bundle getEffectiveUserRestrictions(int userId) {
927 synchronized (mRestrictionsLock) {
928 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
929 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700930 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700931 mCachedEffectiveUserRestrictions.put(userId, restrictions);
932 }
933 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700934 }
935 }
936
Makoto Onuki068c54a2015-10-13 14:34:03 -0700937 /** @return a specific user restriction that's in effect currently. */
938 @Override
939 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800940 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
941 return false;
942 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700943 Bundle restrictions = getEffectiveUserRestrictions(userId);
944 return restrictions != null && restrictions.getBoolean(restrictionKey);
945 }
946
947 /**
948 * @return UserRestrictions that are in effect currently. This always returns a new
949 * {@link Bundle}.
950 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700951 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800952 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800953 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800954 }
955
956 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000957 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
958 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800959 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
960 return false;
961 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000962 synchronized (mRestrictionsLock) {
963 Bundle bundle = mBaseUserRestrictions.get(userId);
964 return (bundle != null && bundle.getBoolean(restrictionKey, false));
965 }
966 }
967
968 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700969 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700970 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800971 if (!UserRestrictionsUtils.isValidRestriction(key)) {
972 return;
973 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700974 synchronized (mRestrictionsLock) {
975 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
976 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800977 final Bundle newRestrictions = UserRestrictionsUtils.clone(
978 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700979 newRestrictions.putBoolean(key, value);
980
Fyodor Kupolov82402752015-10-28 14:54:51 -0700981 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700982 }
983 }
984
Makoto Onuki068c54a2015-10-13 14:34:03 -0700985 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800986 * Optionally updating user restrictions, calculate the effective user restrictions and also
987 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700988 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800989 * @param newRestrictions User restrictions to set.
990 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700991 * @param userId target user ID.
992 */
993 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700994 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700995 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800996
997 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
998 mAppliedUserRestrictions.get(userId));
999
1000 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001001 if (newRestrictions != null) {
1002 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001003 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1004
1005 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001006 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1007 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001008
1009 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1010 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001011 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001012 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001013 }
1014
Fyodor Kupolov82402752015-10-28 14:54:51 -07001015 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001016
Makoto Onuki759a7632015-10-28 16:43:10 -07001017 mCachedEffectiveUserRestrictions.put(userId, effective);
1018
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001019 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001020 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001021 debug("Applying user restrictions: userId=" + userId
1022 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001023 }
1024
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001025 if (mAppOpsService != null) { // We skip it until system-ready.
1026 final long token = Binder.clearCallingIdentity();
1027 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001028 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001029 } catch (RemoteException e) {
1030 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1031 } finally {
1032 Binder.restoreCallingIdentity(token);
1033 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001034 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001035
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001036 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001037
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001038 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001039 }
1040
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001041 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001042 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001043 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1044 // actually, but we still need some kind of synchronization otherwise we might end up
1045 // calling listeners out-of-order, thus "LR".
1046
1047 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1048 return;
1049 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001050
1051 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1052 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1053
1054 mHandler.post(new Runnable() {
1055 @Override
1056 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001057 UserRestrictionsUtils.applyUserRestrictions(
1058 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001059
Makoto Onukid45a4a22015-11-02 17:17:38 -08001060 final UserRestrictionsListener[] listeners;
1061 synchronized (mUserRestrictionsListeners) {
1062 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1063 mUserRestrictionsListeners.toArray(listeners);
1064 }
1065 for (int i = 0; i < listeners.length; i++) {
1066 listeners[i].onUserRestrictionsChanged(userId,
1067 newRestrictionsFinal, prevRestrictionsFinal);
1068 }
1069 }
1070 });
1071 }
1072
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001073 // Package private for the inner class.
1074 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001075 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001076 }
1077
1078 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001079 // Package private for the inner class.
1080 void applyUserRestrictionsForAllUsersLR() {
1081 if (DBG) {
1082 debug("applyUserRestrictionsForAllUsersLR");
1083 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001084 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001085 mCachedEffectiveUserRestrictions.clear();
1086
Makoto Onuki068c54a2015-10-13 14:34:03 -07001087 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1088 // it on a handler.
1089 final Runnable r = new Runnable() {
1090 @Override
1091 public void run() {
1092 // Then get the list of running users.
1093 final int[] runningUsers;
1094 try {
1095 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1096 } catch (RemoteException e) {
1097 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1098 return;
1099 }
1100 // Then re-calculate the effective restrictions and apply, only for running users.
1101 // It's okay if a new user has started after the getRunningUserIds() call,
1102 // because we'll do the same thing (re-calculate the restrictions and apply)
1103 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001104 synchronized (mRestrictionsLock) {
1105 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001106 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001107 }
1108 }
1109 }
1110 };
1111 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001112 }
1113
Amith Yamasani258848d2012-08-10 17:06:33 -07001114 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001115 * Check if we've hit the limit of how many users can be created.
1116 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001117 private boolean isUserLimitReached() {
1118 int count;
1119 synchronized (mUsersLock) {
1120 count = getAliveUsersExcludingGuestsCountLU();
1121 }
1122 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001123 }
1124
1125 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001126 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001127 checkManageUsersPermission("check if more managed profiles can be added.");
1128 if (ActivityManager.isLowRamDeviceStatic()) {
1129 return false;
1130 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001131 if (!mContext.getPackageManager().hasSystemFeature(
1132 PackageManager.FEATURE_MANAGED_USERS)) {
1133 return false;
1134 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001135 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001136 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1137 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1138 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001139 return false;
1140 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001141 synchronized(mUsersLock) {
1142 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001143 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001144 return false;
1145 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001146 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1147 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001148 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001149 return usersCountAfterRemoving == 1
1150 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001151 }
1152 }
1153
Fyodor Kupolov82402752015-10-28 14:54:51 -07001154 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001155 int aliveUserCount = 0;
1156 final int totalUserCount = mUsers.size();
1157 // Skip over users being removed
1158 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001159 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001160 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001161 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001162 aliveUserCount++;
1163 }
1164 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001165 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001166 }
1167
1168 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001169 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001170 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1171 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1172 * permissions can make certain calls to the UserManager.
1173 *
1174 * @param message used as message if SecurityException is thrown
1175 * @throws SecurityException if the caller does not have enough privilege.
1176 */
1177 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1178 final int uid = Binder.getCallingUid();
1179 if (uid != Process.SYSTEM_UID && uid != 0
1180 && ActivityManager.checkComponentPermission(
1181 Manifest.permission.MANAGE_USERS,
1182 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1183 && ActivityManager.checkComponentPermission(
1184 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1185 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1186 throw new SecurityException(
1187 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1188 + message);
1189 }
1190 }
1191
1192 /**
1193 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001194 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001195 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001196 *
1197 * @param message used as message if SecurityException is thrown
1198 * @throws SecurityException if the caller is not system or root
1199 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001200 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001201 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001202 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001203 && ActivityManager.checkComponentPermission(
1204 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001205 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1206 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1207 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001208 }
1209
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001210 /**
1211 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1212 * UserManager.
1213 *
1214 * @param message used as message if SecurityException is thrown
1215 * @throws SecurityException if the caller is not system or root
1216 */
1217 private static void checkSystemOrRoot(String message) {
1218 final int uid = Binder.getCallingUid();
1219 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1220 throw new SecurityException("Only system may: " + message);
1221 }
1222 }
1223
Fyodor Kupolov82402752015-10-28 14:54:51 -07001224 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001225 try {
1226 File dir = new File(mUsersDir, Integer.toString(info.id));
1227 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001228 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001229 if (!dir.exists()) {
1230 dir.mkdir();
1231 FileUtils.setPermissions(
1232 dir.getPath(),
1233 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1234 -1, -1);
1235 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001236 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001237 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001238 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001239 info.iconPath = file.getAbsolutePath();
1240 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001241 try {
1242 os.close();
1243 } catch (IOException ioe) {
1244 // What the ... !
1245 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001246 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001247 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001248 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001249 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001250 }
1251
Amith Yamasani0b285492011-04-14 17:35:23 -07001252 /**
1253 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1254 * cache it elsewhere.
1255 * @return the array of user ids.
1256 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001257 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001258 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001259 return mUserIds;
1260 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001261 }
1262
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001263 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001264 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001265 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001266 return;
1267 }
1268 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001269 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001270 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001271 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001272 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001273 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001274 int type;
1275 while ((type = parser.next()) != XmlPullParser.START_TAG
1276 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001277 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001278 }
1279
1280 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001281 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001282 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001283 return;
1284 }
1285
Amith Yamasani2a003292012-08-14 18:25:45 -07001286 mNextSerialNumber = -1;
1287 if (parser.getName().equals(TAG_USERS)) {
1288 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1289 if (lastSerialNumber != null) {
1290 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1291 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001292 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1293 if (versionNumber != null) {
1294 mUserVersion = Integer.parseInt(versionNumber);
1295 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001296 }
1297
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001298 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1299
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001300 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301301 if (type == XmlPullParser.START_TAG) {
1302 final String name = parser.getName();
1303 if (name.equals(TAG_USER)) {
1304 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001305
Amith Yamasani12747872015-12-07 14:19:49 -08001306 UserData userData = readUserLP(Integer.parseInt(id));
1307
1308 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001309 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001310 mUsers.put(userData.info.id, userData);
1311 if (mNextSerialNumber < 0
1312 || mNextSerialNumber <= userData.info.id) {
1313 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001314 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301315 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001316 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301317 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001318 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1319 && type != XmlPullParser.END_TAG) {
1320 if (type == XmlPullParser.START_TAG) {
1321 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001322 synchronized (mGuestRestrictions) {
1323 UserRestrictionsUtils
1324 .readRestrictions(parser, mGuestRestrictions);
1325 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001326 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1327 ) {
1328 UserRestrictionsUtils.readRestrictions(parser,
1329 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001330 }
1331 break;
1332 }
1333 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001334 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001335 }
1336 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001337 synchronized (mRestrictionsLock) {
1338 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1339 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001340 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001341 upgradeIfNecessaryLP();
1342 } catch (IOException | XmlPullParserException e) {
1343 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001344 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001345 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001346 }
1347 }
1348
Amith Yamasani6f34b412012-10-22 18:19:27 -07001349 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001350 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001351 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001352 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001353 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001354 int userVersion = mUserVersion;
1355 if (userVersion < 1) {
1356 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001357 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1358 if ("Primary".equals(userData.info.name)) {
1359 userData.info.name =
1360 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1361 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001362 }
1363 userVersion = 1;
1364 }
1365
Amith Yamasanibc9625052012-11-15 14:39:18 -08001366 if (userVersion < 2) {
1367 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001368 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1369 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1370 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1371 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001372 }
1373 userVersion = 2;
1374 }
1375
Amith Yamasani350962c2013-08-06 11:18:53 -07001376
Amith Yamasani5e486f52013-08-07 11:06:44 -07001377 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001378 userVersion = 4;
1379 }
1380
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001381 if (userVersion < 5) {
1382 initDefaultGuestRestrictions();
1383 userVersion = 5;
1384 }
1385
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001386 if (userVersion < 6) {
1387 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001388 synchronized (mUsersLock) {
1389 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001390 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001391 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001392 if (!splitSystemUser && userData.info.isRestricted()
1393 && (userData.info.restrictedProfileParentId
1394 == UserInfo.NO_PROFILE_GROUP_ID)) {
1395 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1396 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001397 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001398 }
1399 }
1400 userVersion = 6;
1401 }
1402
Amith Yamasani6f34b412012-10-22 18:19:27 -07001403 if (userVersion < USER_VERSION) {
1404 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1405 + USER_VERSION);
1406 } else {
1407 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001408
1409 if (originalVersion < mUserVersion) {
1410 writeUserListLP();
1411 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001412 }
1413 }
1414
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001415 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001416 int flags = UserInfo.FLAG_INITIALIZED;
1417 // In split system user mode, the admin and primary flags are assigned to the first human
1418 // user.
1419 if (!UserManager.isSplitSystemUser()) {
1420 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1421 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001422 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001423 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001424 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001425 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001426 UserData userData = new UserData();
1427 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001428 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001429 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001430 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001431 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001432 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001433
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001434 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001435 synchronized (mRestrictionsLock) {
1436 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1437 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001438
Fyodor Kupolov82402752015-10-28 14:54:51 -07001439 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001440 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001441
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001442 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001443 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001444 }
1445
Amith Yamasani12747872015-12-07 14:19:49 -08001446 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001447 if (DBG) {
1448 debug("scheduleWriteUser");
1449 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001450 // No need to wrap it within a lock -- worst case, we'll just post the same message
1451 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001452 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1453 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001454 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1455 }
1456 }
1457
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001458 /*
1459 * Writes the user file in this format:
1460 *
1461 * <user flags="20039023" id="0">
1462 * <name>Primary</name>
1463 * </user>
1464 */
Amith Yamasani12747872015-12-07 14:19:49 -08001465 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001466 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001467 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001468 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001469 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001470 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001471 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001472 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001473 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1474
1475 // XmlSerializer serializer = XmlUtils.serializerInstance();
1476 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001477 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001478 serializer.startDocument(null, true);
1479 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1480
Amith Yamasani12747872015-12-07 14:19:49 -08001481 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001482 serializer.startTag(null, TAG_USER);
1483 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001484 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001485 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001486 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1487 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1488 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001489 if (userInfo.iconPath != null) {
1490 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1491 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001492 if (userInfo.partial) {
1493 serializer.attribute(null, ATTR_PARTIAL, "true");
1494 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001495 if (userInfo.guestToRemove) {
1496 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1497 }
Kenny Guy2a764942014-04-02 13:29:20 +01001498 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1499 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1500 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001501 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001502 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1503 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1504 Integer.toString(userInfo.restrictedProfileParentId));
1505 }
Amith Yamasani12747872015-12-07 14:19:49 -08001506 // Write seed data
1507 if (userData.persistSeedData) {
1508 if (userData.seedAccountName != null) {
1509 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1510 }
1511 if (userData.seedAccountType != null) {
1512 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1513 }
1514 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001515 serializer.startTag(null, TAG_NAME);
1516 serializer.text(userInfo.name);
1517 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001518 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001519 UserRestrictionsUtils.writeRestrictions(serializer,
1520 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1521 UserRestrictionsUtils.writeRestrictions(serializer,
1522 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1523 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001524 }
Amith Yamasani12747872015-12-07 14:19:49 -08001525
1526 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001527 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001528 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001529 serializer.endTag(null, TAG_ACCOUNT);
1530 }
1531
Amith Yamasani12747872015-12-07 14:19:49 -08001532 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1533 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1534 userData.seedAccountOptions.saveToXml(serializer);
1535 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1536 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001537 serializer.endTag(null, TAG_USER);
1538
1539 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001540 userFile.finishWrite(fos);
1541 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001542 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001543 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001544 }
1545 }
1546
1547 /*
1548 * Writes the user list file in this format:
1549 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001550 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001551 * <user id="0"></user>
1552 * <user id="2"></user>
1553 * </users>
1554 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001555 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001556 if (DBG) {
1557 debug("writeUserList");
1558 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001559 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001560 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001561 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001562 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001563 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1564
1565 // XmlSerializer serializer = XmlUtils.serializerInstance();
1566 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001567 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001568 serializer.startDocument(null, true);
1569 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1570
1571 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001572 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001573 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001574
Adam Lesinskieddeb492014-09-08 17:50:03 -07001575 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001576 synchronized (mGuestRestrictions) {
1577 UserRestrictionsUtils
1578 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1579 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301580 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001581 synchronized (mRestrictionsLock) {
1582 UserRestrictionsUtils.writeRestrictions(serializer,
1583 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1584 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001585 int[] userIdsToWrite;
1586 synchronized (mUsersLock) {
1587 userIdsToWrite = new int[mUsers.size()];
1588 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001589 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001590 userIdsToWrite[i] = user.id;
1591 }
1592 }
1593 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001594 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001595 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001596 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001597 }
1598
1599 serializer.endTag(null, TAG_USERS);
1600
1601 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001602 userListFile.finishWrite(fos);
1603 } catch (Exception e) {
1604 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001605 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001606 }
1607 }
1608
Amith Yamasani12747872015-12-07 14:19:49 -08001609 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001610 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001611 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001612 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001613 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001614 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001615 long creationTime = 0L;
1616 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001617 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001618 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001619 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001620 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001621 boolean persistSeedData = false;
1622 String seedAccountName = null;
1623 String seedAccountType = null;
1624 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001625 Bundle baseRestrictions = new Bundle();
1626 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001627
1628 FileInputStream fis = null;
1629 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001630 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001631 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001632 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001633 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001634 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001635 int type;
1636 while ((type = parser.next()) != XmlPullParser.START_TAG
1637 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001638 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001639 }
1640
1641 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001642 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001643 return null;
1644 }
1645
1646 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001647 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1648 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001649 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001650 return null;
1651 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001652 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1653 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001654 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001655 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1656 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001657 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1658 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001659 restrictedProfileParentId = readIntAttribute(parser,
1660 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001661 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1662 if ("true".equals(valueString)) {
1663 partial = true;
1664 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001665 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1666 if ("true".equals(valueString)) {
1667 guestToRemove = true;
1668 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001669
Amith Yamasani12747872015-12-07 14:19:49 -08001670 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1671 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1672 if (seedAccountName != null || seedAccountType != null) {
1673 persistSeedData = true;
1674 }
1675
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001676 int outerDepth = parser.getDepth();
1677 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1678 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1679 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1680 continue;
1681 }
1682 String tag = parser.getName();
1683 if (TAG_NAME.equals(tag)) {
1684 type = parser.next();
1685 if (type == XmlPullParser.TEXT) {
1686 name = parser.getText();
1687 }
1688 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001689 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1690 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1691 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001692 } else if (TAG_ACCOUNT.equals(tag)) {
1693 type = parser.next();
1694 if (type == XmlPullParser.TEXT) {
1695 account = parser.getText();
1696 }
Amith Yamasani12747872015-12-07 14:19:49 -08001697 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1698 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1699 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001700 }
1701 }
1702 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001703
Amith Yamasani12747872015-12-07 14:19:49 -08001704 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001705 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001706 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001707 userInfo.creationTime = creationTime;
1708 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001709 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001710 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001711 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001712 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001713
1714 // Create the UserData object that's internal to this class
1715 UserData userData = new UserData();
1716 userData.info = userInfo;
1717 userData.account = account;
1718 userData.seedAccountName = seedAccountName;
1719 userData.seedAccountType = seedAccountType;
1720 userData.persistSeedData = persistSeedData;
1721 userData.seedAccountOptions = seedAccountOptions;
1722
Makoto Onuki068c54a2015-10-13 14:34:03 -07001723 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001724 mBaseUserRestrictions.put(id, baseRestrictions);
1725 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001726 }
Amith Yamasani12747872015-12-07 14:19:49 -08001727 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001728 } catch (IOException ioe) {
1729 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001730 } finally {
1731 if (fis != null) {
1732 try {
1733 fis.close();
1734 } catch (IOException e) {
1735 }
1736 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001737 }
1738 return null;
1739 }
1740
Amith Yamasani920ace02012-09-20 22:15:37 -07001741 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1742 String valueString = parser.getAttributeValue(null, attr);
1743 if (valueString == null) return defaultValue;
1744 try {
1745 return Integer.parseInt(valueString);
1746 } catch (NumberFormatException nfe) {
1747 return defaultValue;
1748 }
1749 }
1750
1751 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1752 String valueString = parser.getAttributeValue(null, attr);
1753 if (valueString == null) return defaultValue;
1754 try {
1755 return Long.parseLong(valueString);
1756 } catch (NumberFormatException nfe) {
1757 return defaultValue;
1758 }
1759 }
1760
Amith Yamasanib82add22013-07-09 11:24:44 -07001761 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001762 * Removes the app restrictions file for a specific package and user id, if it exists.
1763 */
1764 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1765 synchronized (mPackagesLock) {
1766 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001767 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001768 if (resFile.exists()) {
1769 resFile.delete();
1770 }
1771 }
1772 }
1773
Kenny Guya52dc3e2014-02-11 15:33:14 +00001774 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001775 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001776 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001777 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001778 }
1779
Amith Yamasani258848d2012-08-10 17:06:33 -07001780 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001781 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001782 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001783 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001784 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001785
Jessica Hummelbe81c802014-04-22 15:49:22 +01001786 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001787 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001788 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1789 return null;
1790 }
phweisse9c44062016-02-10 12:57:38 +01001791 return createUserInternalUnchecked(name, flags, parentId);
1792 }
1793
1794 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001795 if (ActivityManager.isLowRamDeviceStatic()) {
1796 return null;
1797 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001798 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001799 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001800 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001801 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001802 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001803 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001804 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001805 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001806 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001807 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001808 if (parentId != UserHandle.USER_NULL) {
1809 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001810 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001811 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001812 if (parent == null) return null;
1813 }
1814 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1815 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1816 return null;
1817 }
1818 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1819 // If we're not adding a guest user or a managed profile and the limit has
1820 // been reached, cannot add a user.
1821 return null;
1822 }
1823 // If we're adding a guest and there already exists one, bail.
1824 if (isGuest && findCurrentGuestUser() != null) {
1825 return null;
1826 }
1827 // In legacy mode, restricted profile's parent can only be the owner user
1828 if (isRestricted && !UserManager.isSplitSystemUser()
1829 && (parentId != UserHandle.USER_SYSTEM)) {
1830 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1831 return null;
1832 }
1833 if (isRestricted && UserManager.isSplitSystemUser()) {
1834 if (parent == null) {
1835 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1836 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001837 return null;
1838 }
Amith Yamasani12747872015-12-07 14:19:49 -08001839 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001840 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1841 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001842 return null;
1843 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001844 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01001845 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
1846 Log.e(LOG_TAG,
1847 "Ephemeral users are supported on split-system-user systems only.");
1848 return null;
1849 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001850 // In split system user mode, we assign the first human user the primary flag.
1851 // And if there is no device owner, we also assign the admin flag to primary user.
1852 if (UserManager.isSplitSystemUser()
1853 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1854 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001855 synchronized (mUsersLock) {
1856 if (!mIsDeviceManaged) {
1857 flags |= UserInfo.FLAG_ADMIN;
1858 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001859 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001860 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001861
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001862 userId = getNextAvailableId();
1863 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001864 boolean ephemeralGuests = Resources.getSystem()
1865 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001866
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001867 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001868 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1869 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1870 || (parent != null && parent.info.isEphemeral())) {
1871 flags |= UserInfo.FLAG_EPHEMERAL;
1872 }
1873
1874 userInfo = new UserInfo(userId, name, null, flags);
1875 userInfo.serialNumber = mNextSerialNumber++;
1876 long now = System.currentTimeMillis();
1877 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1878 userInfo.partial = true;
1879 userData = new UserData();
1880 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001881 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001882 }
1883 writeUserListLP();
1884 if (parent != null) {
1885 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001886 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1887 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001888 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001889 }
Amith Yamasani12747872015-12-07 14:19:49 -08001890 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001891 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001892 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1893 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001894 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001895 }
Amith Yamasani12747872015-12-07 14:19:49 -08001896 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001897 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001898 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001899 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001900 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001901 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkey47f71082016-02-01 17:03:54 -07001902 prepareUserStorage(userId, userInfo.serialNumber,
1903 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001904 mPm.createNewUser(userId);
1905 userInfo.partial = false;
1906 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001907 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001908 }
1909 updateUserIds();
1910 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001911 if (isGuest) {
1912 synchronized (mGuestRestrictions) {
1913 restrictions.putAll(mGuestRestrictions);
1914 }
1915 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001916 synchronized (mRestrictionsLock) {
1917 mBaseUserRestrictions.append(userId, restrictions);
1918 }
1919 mPm.newUserCreated(userId);
1920 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1921 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1922 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1923 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001924 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001925 } finally {
1926 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001927 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001928 return userInfo;
1929 }
1930
Amith Yamasani0b285492011-04-14 17:35:23 -07001931 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001932 * @hide
1933 */
Amith Yamasani12747872015-12-07 14:19:49 -08001934 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001935 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1936 checkManageUsersPermission("setupRestrictedProfile");
1937 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1938 if (user == null) {
1939 return null;
1940 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08001941 long identity = Binder.clearCallingIdentity();
1942 try {
1943 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1944 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1945 // the putIntForUser() will fail.
1946 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1947 android.provider.Settings.Secure.LOCATION_MODE,
1948 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1949 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1950 } finally {
1951 Binder.restoreCallingIdentity(identity);
1952 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001953 return user;
1954 }
1955
1956 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001957 * Find the current guest user. If the Guest user is partial,
1958 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001959 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001960 private UserInfo findCurrentGuestUser() {
1961 synchronized (mUsersLock) {
1962 final int size = mUsers.size();
1963 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001964 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001965 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1966 return user;
1967 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001968 }
1969 }
1970 return null;
1971 }
1972
1973 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001974 * Mark this guest user for deletion to allow us to create another guest
1975 * and switch to that user before actually removing this guest.
1976 * @param userHandle the userid of the current guest
1977 * @return whether the user could be marked for deletion
1978 */
Amith Yamasani12747872015-12-07 14:19:49 -08001979 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07001980 public boolean markGuestForDeletion(int userHandle) {
1981 checkManageUsersPermission("Only the system can remove users");
1982 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1983 UserManager.DISALLOW_REMOVE_USER, false)) {
1984 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1985 return false;
1986 }
1987
1988 long ident = Binder.clearCallingIdentity();
1989 try {
Amith Yamasani12747872015-12-07 14:19:49 -08001990 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07001991 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001992 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001993 userData = mUsers.get(userHandle);
1994 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001995 return false;
1996 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001997 }
Amith Yamasani12747872015-12-07 14:19:49 -08001998 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07001999 return false;
2000 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002001 // We set this to a guest user that is to be removed. This is a temporary state
2002 // where we are allowed to add new Guest users, even if this one is still not
2003 // removed. This user will still show up in getUserInfo() calls.
2004 // If we don't get around to removing this Guest user, it will be purged on next
2005 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002006 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002007 // Mark it as disabled, so that it isn't returned any more when
2008 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002009 userData.info.flags |= UserInfo.FLAG_DISABLED;
2010 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002011 }
2012 } finally {
2013 Binder.restoreCallingIdentity(ident);
2014 }
2015 return true;
2016 }
2017
2018 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002019 * Removes a user and all data directories created for that user. This method should be called
2020 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002021 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002022 */
Amith Yamasani12747872015-12-07 14:19:49 -08002023 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002024 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002025 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002026 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2027 UserManager.DISALLOW_REMOVE_USER, false)) {
2028 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2029 return false;
2030 }
2031
Kenny Guyee58b4f2014-05-23 15:19:53 +01002032 long ident = Binder.clearCallingIdentity();
2033 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002034 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002035 int currentUser = ActivityManager.getCurrentUser();
2036 if (currentUser == userHandle) {
2037 Log.w(LOG_TAG, "Current user cannot be removed");
2038 return false;
2039 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002040 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002041 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002042 userData = mUsers.get(userHandle);
2043 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002044 return false;
2045 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002046
Fyodor Kupolov82402752015-10-28 14:54:51 -07002047 // We remember deleted user IDs to prevent them from being
2048 // reused during the current boot; they can still be reused
2049 // after a reboot.
2050 mRemovingUserIds.put(userHandle, true);
2051 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002052
Kenny Guyee58b4f2014-05-23 15:19:53 +01002053 try {
2054 mAppOpsService.removeUser(userHandle);
2055 } catch (RemoteException e) {
2056 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2057 }
2058 // Set this to a partially created user, so that the user will be purged
2059 // on next startup, in case the runtime stops now before stopping and
2060 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002061 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002062 // Mark it as disabled, so that it isn't returned any more when
2063 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002064 userData.info.flags |= UserInfo.FLAG_DISABLED;
2065 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002066 }
2067
Amith Yamasani12747872015-12-07 14:19:49 -08002068 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2069 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002070 // Send broadcast to notify system that the user removed was a
2071 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002072 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002073 }
2074
2075 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2076 int res;
2077 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002078 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2079 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002080 @Override
2081 public void userStopped(int userId) {
2082 finishRemoveUser(userId);
2083 }
2084 @Override
2085 public void userStopAborted(int userId) {
2086 }
2087 });
2088 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002089 return false;
2090 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002091 return res == ActivityManager.USER_OP_SUCCESS;
2092 } finally {
2093 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002094 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002095 }
2096
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002097 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002098 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002099 // Let other services shutdown any activity and clean up their state before completely
2100 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002101 long ident = Binder.clearCallingIdentity();
2102 try {
2103 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2104 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002105 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2106 android.Manifest.permission.MANAGE_USERS,
2107
2108 new BroadcastReceiver() {
2109 @Override
2110 public void onReceive(Context context, Intent intent) {
2111 if (DBG) {
2112 Slog.i(LOG_TAG,
2113 "USER_REMOVED broadcast sent, cleaning up user data "
2114 + userHandle);
2115 }
2116 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002117 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002118 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002119 // Clean up any ActivityManager state
2120 LocalServices.getService(ActivityManagerInternal.class)
2121 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002122 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002123 }
2124 }.start();
2125 }
2126 },
2127
2128 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002129 } finally {
2130 Binder.restoreCallingIdentity(ident);
2131 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002132 }
2133
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002134 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002135 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002136 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002137 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002138
2139 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002140 synchronized (mUsersLock) {
2141 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002142 mIsUserManaged.delete(userHandle);
2143 }
2144 synchronized (mRestrictionsLock) {
2145 mBaseUserRestrictions.remove(userHandle);
2146 mAppliedUserRestrictions.remove(userHandle);
2147 mCachedEffectiveUserRestrictions.remove(userHandle);
2148 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002149 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002150 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002151 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002152 userFile.delete();
2153 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002154 synchronized (mPackagesLock) {
2155 writeUserListLP();
2156 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002157 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002158 File userDir = Environment.getUserSystemDirectory(userHandle);
2159 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2160 if (userDir.renameTo(renamedUserDir)) {
2161 removeDirectoryRecursive(renamedUserDir);
2162 } else {
2163 removeDirectoryRecursive(userDir);
2164 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002165 }
2166
Amith Yamasani61f57372012-08-31 12:12:28 -07002167 private void removeDirectoryRecursive(File parent) {
2168 if (parent.isDirectory()) {
2169 String[] files = parent.list();
2170 for (String filename : files) {
2171 File child = new File(parent, filename);
2172 removeDirectoryRecursive(child);
2173 }
2174 }
2175 parent.delete();
2176 }
2177
Kenny Guyf8d3a232014-05-15 16:09:52 +01002178 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002179 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002180 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2181 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002182 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002183 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002184 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002185 }
2186
Amith Yamasani2a003292012-08-14 18:25:45 -07002187 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002188 public Bundle getApplicationRestrictions(String packageName) {
2189 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2190 }
2191
2192 @Override
2193 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002194 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002195 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002196 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002197 }
2198 synchronized (mPackagesLock) {
2199 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002200 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002201 }
2202 }
2203
2204 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002205 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002206 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002207 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002208 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002209 if (restrictions == null || restrictions.isEmpty()) {
2210 cleanAppRestrictionsForPackage(packageName, userId);
2211 } else {
2212 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002213 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002214 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002215 }
Robin Lee66e5d962014-04-09 16:44:21 +01002216
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002217 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2218 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2219 changeIntent.setPackage(packageName);
2220 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2221 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002222 }
2223
2224 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002225 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002226 try {
2227 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002228 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002229 } catch (NameNotFoundException nnfe) {
2230 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002231 } finally {
2232 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002233 }
2234 }
2235
Fyodor Kupolov82402752015-10-28 14:54:51 -07002236 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002237 AtomicFile restrictionsFile =
2238 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2239 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002240 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002241 }
2242
2243 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002244 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002245 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002246 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002247 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002248 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002249 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002250
2251 FileInputStream fis = null;
2252 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002253 fis = restrictionsFile.openRead();
2254 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002255 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002256 XmlUtils.nextElement(parser);
2257 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002258 Slog.e(LOG_TAG, "Unable to read restrictions file "
2259 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002260 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002261 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002262 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2263 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002264 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002265 } catch (IOException|XmlPullParserException e) {
2266 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002267 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002268 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002269 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002270 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002271 }
2272
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002273 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2274 XmlPullParser parser) throws XmlPullParserException, IOException {
2275 int type = parser.getEventType();
2276 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2277 String key = parser.getAttributeValue(null, ATTR_KEY);
2278 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2279 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2280 if (multiple != null) {
2281 values.clear();
2282 int count = Integer.parseInt(multiple);
2283 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2284 if (type == XmlPullParser.START_TAG
2285 && parser.getName().equals(TAG_VALUE)) {
2286 values.add(parser.nextText().trim());
2287 count--;
2288 }
2289 }
2290 String [] valueStrings = new String[values.size()];
2291 values.toArray(valueStrings);
2292 restrictions.putStringArray(key, valueStrings);
2293 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2294 restrictions.putBundle(key, readBundleEntry(parser, values));
2295 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2296 final int outerDepth = parser.getDepth();
2297 ArrayList<Bundle> bundleList = new ArrayList<>();
2298 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2299 Bundle childBundle = readBundleEntry(parser, values);
2300 bundleList.add(childBundle);
2301 }
2302 restrictions.putParcelableArray(key,
2303 bundleList.toArray(new Bundle[bundleList.size()]));
2304 } else {
2305 String value = parser.nextText().trim();
2306 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2307 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2308 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2309 restrictions.putInt(key, Integer.parseInt(value));
2310 } else {
2311 restrictions.putString(key, value);
2312 }
2313 }
2314 }
2315 }
2316
2317 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2318 throws IOException, XmlPullParserException {
2319 Bundle childBundle = new Bundle();
2320 final int outerDepth = parser.getDepth();
2321 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2322 readEntry(childBundle, values, parser);
2323 }
2324 return childBundle;
2325 }
2326
Fyodor Kupolov82402752015-10-28 14:54:51 -07002327 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002328 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002329 AtomicFile restrictionsFile = new AtomicFile(
2330 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002331 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002332 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002333 }
2334
2335 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002336 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002337 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002338 try {
2339 fos = restrictionsFile.startWrite();
2340 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2341
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002342 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002343 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002344 serializer.startDocument(null, true);
2345 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2346
2347 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002348 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002349 serializer.endTag(null, TAG_RESTRICTIONS);
2350
2351 serializer.endDocument();
2352 restrictionsFile.finishWrite(fos);
2353 } catch (Exception e) {
2354 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002355 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2356 }
2357 }
2358
2359 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2360 throws IOException {
2361 for (String key : restrictions.keySet()) {
2362 Object value = restrictions.get(key);
2363 serializer.startTag(null, TAG_ENTRY);
2364 serializer.attribute(null, ATTR_KEY, key);
2365
2366 if (value instanceof Boolean) {
2367 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2368 serializer.text(value.toString());
2369 } else if (value instanceof Integer) {
2370 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2371 serializer.text(value.toString());
2372 } else if (value == null || value instanceof String) {
2373 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2374 serializer.text(value != null ? (String) value : "");
2375 } else if (value instanceof Bundle) {
2376 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2377 writeBundle((Bundle) value, serializer);
2378 } else if (value instanceof Parcelable[]) {
2379 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2380 Parcelable[] array = (Parcelable[]) value;
2381 for (Parcelable parcelable : array) {
2382 if (!(parcelable instanceof Bundle)) {
2383 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2384 }
2385 serializer.startTag(null, TAG_ENTRY);
2386 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2387 writeBundle((Bundle) parcelable, serializer);
2388 serializer.endTag(null, TAG_ENTRY);
2389 }
2390 } else {
2391 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2392 String[] values = (String[]) value;
2393 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2394 for (String choice : values) {
2395 serializer.startTag(null, TAG_VALUE);
2396 serializer.text(choice != null ? choice : "");
2397 serializer.endTag(null, TAG_VALUE);
2398 }
2399 }
2400 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002401 }
2402 }
2403
2404 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002405 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002406 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002407 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002408 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002409 }
2410 }
2411
2412 @Override
2413 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002414 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002415 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002416 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002417 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002418 }
2419 // Not found
2420 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002421 }
2422 }
2423
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002424 @Override
2425 public long getUserCreationTime(int userHandle) {
2426 int callingUserId = UserHandle.getCallingUserId();
2427 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002428 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002429 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002430 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002431 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002432 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002433 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002434 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002435 }
2436 }
2437 }
2438 if (userInfo == null) {
2439 throw new SecurityException("userHandle can only be the calling user or a managed "
2440 + "profile associated with this user");
2441 }
2442 return userInfo.creationTime;
2443 }
2444
Amith Yamasani0b285492011-04-14 17:35:23 -07002445 /**
2446 * Caches the list of user ids in an array, adjusting the array size when necessary.
2447 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002448 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002449 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002450 synchronized (mUsersLock) {
2451 final int userSize = mUsers.size();
2452 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002453 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002454 num++;
2455 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002456 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002457 final int[] newUsers = new int[num];
2458 int n = 0;
2459 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002460 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002461 newUsers[n++] = mUsers.keyAt(i);
2462 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002463 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002464 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002465 }
2466 }
2467
2468 /**
Jeff Sharkey47f71082016-02-01 17:03:54 -07002469 * Prepare storage areas for given user on all mounted devices.
2470 */
2471 private void prepareUserStorage(int userId, int userSerial, int flags) {
2472 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2473 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
2474 final String volumeUuid = vol.getFsUuid();
2475 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
2476 }
2477 }
2478
2479 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002480 * Called right before a user is started. This gives us a chance to prepare
2481 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002482 */
2483 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002484 final int userSerial = getUserSerialNumber(userId);
2485 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2486 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002487
2488 if (userId != UserHandle.USER_SYSTEM) {
2489 synchronized (mRestrictionsLock) {
2490 applyUserRestrictionsLR(userId);
2491 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002492 }
2493 }
2494
2495 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002496 * Called right before a user is unlocked. This gives us a chance to prepare
2497 * app storage.
2498 */
2499 public void onBeforeUnlockUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002500 final int userSerial = getUserSerialNumber(userId);
2501 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
2502 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002503 }
2504
2505 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002506 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002507 * @param userId the user that was just foregrounded
2508 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002509 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002510 UserData userData = getUserDataNoChecks(userId);
2511 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002512 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2513 return;
2514 }
2515 long now = System.currentTimeMillis();
2516 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002517 userData.info.lastLoggedInTime = now;
2518 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002519 }
2520 }
2521
2522 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002523 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002524 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2525 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002526 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002527 private int getNextAvailableId() {
2528 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002529 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002530 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002531 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002532 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002533 }
2534 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002535 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002536 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002537 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002538 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002539
Amith Yamasanifc95e702013-09-26 13:20:17 -07002540 private String packageToRestrictionsFileName(String packageName) {
2541 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2542 }
2543
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002544 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002545 * Enforce that serial number stored in user directory inode matches the
2546 * given expected value. Gracefully sets the serial number if currently
2547 * undefined.
2548 *
2549 * @throws IOException when problem extracting serial number, or serial
2550 * number is mismatched.
2551 */
2552 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2553 final int foundSerial = getSerialNumber(file);
2554 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2555
2556 if (foundSerial == -1) {
2557 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2558 try {
2559 setSerialNumber(file, serialNumber);
2560 } catch (IOException e) {
2561 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2562 }
2563
2564 } else if (foundSerial != serialNumber) {
2565 throw new IOException("Found serial number " + foundSerial
2566 + " doesn't match expected " + serialNumber);
2567 }
2568 }
2569
2570 /**
2571 * Set serial number stored in user directory inode.
2572 *
2573 * @throws IOException if serial number was already set
2574 */
2575 private static void setSerialNumber(File file, int serialNumber)
2576 throws IOException {
2577 try {
2578 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2579 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2580 } catch (ErrnoException e) {
2581 throw e.rethrowAsIOException();
2582 }
2583 }
2584
2585 /**
2586 * Return serial number stored in user directory inode.
2587 *
2588 * @return parsed serial number, or -1 if not set
2589 */
2590 private static int getSerialNumber(File file) throws IOException {
2591 try {
2592 final byte[] buf = new byte[256];
2593 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2594 final String serial = new String(buf, 0, len);
2595 try {
2596 return Integer.parseInt(serial);
2597 } catch (NumberFormatException e) {
2598 throw new IOException("Bad serial number: " + serial);
2599 }
2600 } catch (ErrnoException e) {
2601 if (e.errno == OsConstants.ENODATA) {
2602 return -1;
2603 } else {
2604 throw e.rethrowAsIOException();
2605 }
2606 }
2607 }
2608
Amith Yamasani920ace02012-09-20 22:15:37 -07002609 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002610 public void setSeedAccountData(int userId, String accountName, String accountType,
2611 PersistableBundle accountOptions, boolean persist) {
2612 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2613 synchronized (mPackagesLock) {
2614 final UserData userData;
2615 synchronized (mUsersLock) {
2616 userData = getUserDataLU(userId);
2617 if (userData == null) {
2618 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2619 return;
2620 }
2621 userData.seedAccountName = accountName;
2622 userData.seedAccountType = accountType;
2623 userData.seedAccountOptions = accountOptions;
2624 userData.persistSeedData = persist;
2625 }
2626 if (persist) {
2627 writeUserLP(userData);
2628 }
2629 }
2630 }
2631
2632 @Override
2633 public String getSeedAccountName() throws RemoteException {
2634 checkManageUsersPermission("Cannot get seed account information");
2635 synchronized (mUsersLock) {
2636 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2637 return userData.seedAccountName;
2638 }
2639 }
2640
2641 @Override
2642 public String getSeedAccountType() throws RemoteException {
2643 checkManageUsersPermission("Cannot get seed account information");
2644 synchronized (mUsersLock) {
2645 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2646 return userData.seedAccountType;
2647 }
2648 }
2649
2650 @Override
2651 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2652 checkManageUsersPermission("Cannot get seed account information");
2653 synchronized (mUsersLock) {
2654 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2655 return userData.seedAccountOptions;
2656 }
2657 }
2658
2659 @Override
2660 public void clearSeedAccountData() throws RemoteException {
2661 checkManageUsersPermission("Cannot clear seed account information");
2662 synchronized (mPackagesLock) {
2663 UserData userData;
2664 synchronized (mUsersLock) {
2665 userData = getUserDataLU(UserHandle.getCallingUserId());
2666 if (userData == null) return;
2667 userData.clearSeedAccountData();
2668 }
2669 writeUserLP(userData);
2670 }
2671 }
2672
2673 @Override
2674 public boolean someUserHasSeedAccount(String accountName, String accountType)
2675 throws RemoteException {
2676 checkManageUsersPermission("Cannot check seed account information");
2677 synchronized (mUsersLock) {
2678 final int userSize = mUsers.size();
2679 for (int i = 0; i < userSize; i++) {
2680 final UserData data = mUsers.valueAt(i);
2681 if (data.info.isInitialized()) continue;
2682 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2683 continue;
2684 }
2685 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2686 continue;
2687 }
2688 return true;
2689 }
2690 }
2691 return false;
2692 }
2693
2694 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002695 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2696 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2697 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2698 }
2699
2700 int onShellCommand(Shell shell, String cmd) {
2701 if (cmd == null) {
2702 return shell.handleDefaultCommands(cmd);
2703 }
2704
2705 final PrintWriter pw = shell.getOutPrintWriter();
2706 try {
2707 switch(cmd) {
2708 case "list":
2709 return runList(pw);
2710 }
2711 } catch (RemoteException e) {
2712 pw.println("Remote exception: " + e);
2713 }
2714 return -1;
2715 }
2716
2717 private int runList(PrintWriter pw) throws RemoteException {
2718 final IActivityManager am = ActivityManagerNative.getDefault();
2719 final List<UserInfo> users = getUsers(false);
2720 if (users == null) {
2721 pw.println("Error: couldn't get users");
2722 return 1;
2723 } else {
2724 pw.println("Users:");
2725 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002726 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002727 pw.println("\t" + users.get(i).toString() + running);
2728 }
2729 return 0;
2730 }
2731 }
2732
2733 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002734 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2735 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2736 != PackageManager.PERMISSION_GRANTED) {
2737 pw.println("Permission Denial: can't dump UserManager from from pid="
2738 + Binder.getCallingPid()
2739 + ", uid=" + Binder.getCallingUid()
2740 + " without permission "
2741 + android.Manifest.permission.DUMP);
2742 return;
2743 }
2744
2745 long now = System.currentTimeMillis();
2746 StringBuilder sb = new StringBuilder();
2747 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002748 synchronized (mUsersLock) {
2749 pw.println("Users:");
2750 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002751 UserData userData = mUsers.valueAt(i);
2752 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002753 continue;
2754 }
Amith Yamasani12747872015-12-07 14:19:49 -08002755 UserInfo userInfo = userData.info;
2756 final int userId = userInfo.id;
2757 pw.print(" "); pw.print(userInfo);
2758 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002759 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002760 pw.print(" <removing> ");
2761 }
Amith Yamasani12747872015-12-07 14:19:49 -08002762 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002763 pw.print(" <partial>");
2764 }
2765 pw.println();
2766 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002767 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002768 pw.println("<unknown>");
2769 } else {
2770 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002771 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002772 sb.append(" ago");
2773 pw.println(sb);
2774 }
2775 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002776 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002777 pw.println("<unknown>");
2778 } else {
2779 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002780 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002781 sb.append(" ago");
2782 pw.println(sb);
2783 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002784 pw.print(" Has profile owner: ");
2785 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002786 pw.println(" Restrictions:");
2787 synchronized (mRestrictionsLock) {
2788 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002789 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002790 pw.println(" Device policy local restrictions:");
2791 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002792 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002793 pw.println(" Effective restrictions:");
2794 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002795 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002796 }
Amith Yamasani12747872015-12-07 14:19:49 -08002797
2798 if (userData.account != null) {
2799 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002800 pw.println();
2801 }
Amith Yamasani12747872015-12-07 14:19:49 -08002802
2803 if (userData.seedAccountName != null) {
2804 pw.print(" Seed account name: " + userData.seedAccountName);
2805 pw.println();
2806 if (userData.seedAccountType != null) {
2807 pw.print(" account type: " + userData.seedAccountType);
2808 pw.println();
2809 }
2810 if (userData.seedAccountOptions != null) {
2811 pw.print(" account options exist");
2812 pw.println();
2813 }
2814 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002815 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002816 }
Amith Yamasani12747872015-12-07 14:19:49 -08002817 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002818 pw.println(" Device policy global restrictions:");
2819 synchronized (mRestrictionsLock) {
2820 UserRestrictionsUtils
2821 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2822 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002823 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002824 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002825 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002826 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002827 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002828 synchronized (mUsersLock) {
2829 pw.println();
2830 pw.println(" Device managed: " + mIsDeviceManaged);
2831 }
Amith Yamasani12747872015-12-07 14:19:49 -08002832 // Dump some capabilities
2833 pw.println();
2834 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2835 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002836 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2837 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002838 }
2839 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002840
2841 final class MainHandler extends Handler {
2842
2843 @Override
2844 public void handleMessage(Message msg) {
2845 switch (msg.what) {
2846 case WRITE_USER_MSG:
2847 removeMessages(WRITE_USER_MSG, msg.obj);
2848 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002849 int userId = ((UserData) msg.obj).info.id;
2850 UserData userData = getUserDataNoChecks(userId);
2851 if (userData != null) {
2852 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002853 }
2854 }
2855 }
2856 }
2857 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002858
2859 /**
2860 * @param userId
2861 * @return whether the user has been initialized yet
2862 */
2863 boolean isInitialized(int userId) {
2864 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2865 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002866
2867 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002868 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002869 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2870 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002871 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002872 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002873 }
2874
2875 @Override
2876 public Bundle getBaseUserRestrictions(int userId) {
2877 synchronized (mRestrictionsLock) {
2878 return mBaseUserRestrictions.get(userId);
2879 }
2880 }
2881
2882 @Override
2883 public void setBaseUserRestrictionsByDpmsForMigration(
2884 int userId, Bundle baseRestrictions) {
2885 synchronized (mRestrictionsLock) {
2886 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002887 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002888 }
2889
Amith Yamasani12747872015-12-07 14:19:49 -08002890 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002891 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002892 if (userData != null) {
2893 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002894 } else {
2895 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2896 }
2897 }
2898 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002899
2900 @Override
2901 public boolean getUserRestriction(int userId, String key) {
2902 return getUserRestrictions(userId).getBoolean(key);
2903 }
2904
2905 @Override
2906 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2907 synchronized (mUserRestrictionsListeners) {
2908 mUserRestrictionsListeners.add(listener);
2909 }
2910 }
2911
2912 @Override
2913 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2914 synchronized (mUserRestrictionsListeners) {
2915 mUserRestrictionsListeners.remove(listener);
2916 }
2917 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002918
2919 @Override
2920 public void setDeviceManaged(boolean isManaged) {
2921 synchronized (mUsersLock) {
2922 mIsDeviceManaged = isManaged;
2923 }
2924 }
2925
2926 @Override
2927 public void setUserManaged(int userId, boolean isManaged) {
2928 synchronized (mUsersLock) {
2929 mIsUserManaged.put(userId, isManaged);
2930 }
2931 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01002932
2933 @Override
2934 public void setUserIcon(int userId, Bitmap bitmap) {
2935 long ident = Binder.clearCallingIdentity();
2936 try {
2937 synchronized (mPackagesLock) {
2938 UserData userData = getUserDataNoChecks(userId);
2939 if (userData == null || userData.info.partial) {
2940 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
2941 return;
2942 }
2943 writeBitmapLP(userData.info, bitmap);
2944 writeUserLP(userData);
2945 }
2946 sendUserInfoChangedBroadcast(userId);
2947 } finally {
2948 Binder.restoreCallingIdentity(ident);
2949 }
2950 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002951
2952 @Override
2953 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
2954 synchronized (mUsersLock) {
2955 mForceEphemeralUsers = forceEphemeralUsers;
2956 }
2957 }
2958
2959 @Override
2960 public void removeAllUsers() {
2961 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
2962 // Remove the non-system users straight away.
2963 removeNonSystemUsers();
2964 } else {
2965 // Switch to the system user first and then remove the other users.
2966 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
2967 @Override
2968 public void onReceive(Context context, Intent intent) {
2969 int userId =
2970 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2971 if (userId != UserHandle.USER_SYSTEM) {
2972 return;
2973 }
2974 mContext.unregisterReceiver(this);
2975 removeNonSystemUsers();
2976 }
2977 };
2978 IntentFilter userSwitchedFilter = new IntentFilter();
2979 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
2980 mContext.registerReceiver(
2981 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
2982
2983 // Switch to the system user.
2984 ActivityManager am =
2985 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
2986 am.switchUser(UserHandle.USER_SYSTEM);
2987 }
2988 }
phweisse9c44062016-02-10 12:57:38 +01002989
2990 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01002991 public void onEphemeralUserStop(int userId) {
2992 synchronized (mUsersLock) {
2993 UserInfo userInfo = getUserInfoLU(userId);
2994 if (userInfo != null && userInfo.isEphemeral()) {
2995 // Do not allow switching back to the ephemeral user again as the user is going
2996 // to be deleted.
2997 userInfo.flags |= UserInfo.FLAG_DISABLED;
2998 if (userInfo.isGuest()) {
2999 // Indicate that the guest will be deleted after it stops.
3000 userInfo.guestToRemove = true;
3001 }
3002 }
3003 }
3004 }
3005
3006 @Override
phweisse9c44062016-02-10 12:57:38 +01003007 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3008 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3009 // Keep this in sync with UserManager.createUser
3010 if (user != null && !user.isAdmin()) {
3011 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3012 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3013 }
3014 return user;
3015 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003016 }
3017
3018 /* Remove all the users except of the system one. */
3019 private void removeNonSystemUsers() {
3020 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3021 synchronized (mUsersLock) {
3022 final int userSize = mUsers.size();
3023 for (int i = 0; i < userSize; i++) {
3024 UserInfo ui = mUsers.valueAt(i).info;
3025 if (ui.id != UserHandle.USER_SYSTEM) {
3026 usersToRemove.add(ui);
3027 }
3028 }
3029 }
3030 for (UserInfo ui: usersToRemove) {
3031 removeUser(ui.id);
3032 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003033 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003034
3035 private class Shell extends ShellCommand {
3036 @Override
3037 public int onCommand(String cmd) {
3038 return onShellCommand(this, cmd);
3039 }
3040
3041 @Override
3042 public void onHelp() {
3043 final PrintWriter pw = getOutPrintWriter();
3044 pw.println("User manager (user) commands:");
3045 pw.println(" help");
3046 pw.println(" Print this help text.");
3047 pw.println("");
3048 pw.println(" list");
3049 pw.println(" Prints all users on the system.");
3050 }
3051 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003052
3053 private static void debug(String message) {
3054 Log.d(LOG_TAG, message +
3055 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3056 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003057}