blob: 22d09944d13f73c1733f0fec631e8577939bfc71 [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;
Amith Yamasani258848d2012-08-10 17:06:33 -070044import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080045import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010046import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070047import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080048import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070049import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070050import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070051import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040052import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070053import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070054import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070055import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070056import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080057import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010058import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070059import android.os.storage.VolumeInfo;
60import android.system.ErrnoException;
61import android.system.Os;
62import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070063import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070064import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import android.util.Slog;
66import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080067import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070068import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070069import android.util.Xml;
70
Makoto Onuki068c54a2015-10-13 14:34:03 -070071import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070072import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040073import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080074import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080075import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070076import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070077import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000078import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070079import com.android.server.LocalServices;
Jeff Sharkey47f71082016-02-01 17:03:54 -070080
81import libcore.io.IoUtils;
82import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080083
84import org.xmlpull.v1.XmlPullParser;
85import org.xmlpull.v1.XmlPullParserException;
86import org.xmlpull.v1.XmlSerializer;
87
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088import java.io.BufferedOutputStream;
89import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070090import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070091import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070092import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093import java.io.FileOutputStream;
94import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070095import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010096import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097import java.util.ArrayList;
98import java.util.List;
99
Makoto Onuki068c54a2015-10-13 14:34:03 -0700100/**
101 * Service for {@link UserManager}.
102 *
103 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700104 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800105 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700106 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
107 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
108 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700109 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700110public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700111 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800112 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800113 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700114
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800116 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700118 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700120 private static final String ATTR_CREATION_TIME = "created";
121 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700122 private static final String ATTR_SERIAL_NO = "serialNumber";
123 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700124 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700125 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700126 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100127 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700128 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800129 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
130 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530131 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700133 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800134 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800135 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800136 private static final String TAG_ENTRY = "entry";
137 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800138 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800139 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700140 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800141 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700142
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700143 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
144 private static final String ATTR_TYPE_STRING = "s";
145 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700146 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700147 private static final String ATTR_TYPE_BUNDLE = "B";
148 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700149
Amith Yamasani0b285492011-04-14 17:35:23 -0700150 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700151 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700152 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100153 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700154
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800155 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700156 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800157
Amith Yamasani634cf312012-10-04 17:34:21 -0700158 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700159 // We need to keep process uid within Integer.MAX_VALUE.
160 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700161
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700162 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700163
Amith Yamasani920ace02012-09-20 22:15:37 -0700164 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
165
Nicolas Prevotb8186812015-08-06 15:00:03 +0100166 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700167 // without first making sure that the rest of the framework is prepared for it.
168 private static final int MAX_MANAGED_PROFILES = 1;
169
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800170 static final int WRITE_USER_MSG = 1;
171 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530172
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700173 private static final String XATTR_SERIAL = "user.serial";
174
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800175 // Tron counters
176 private static final String TRON_GUEST_CREATED = "users_guest_created";
177 private static final String TRON_USER_CREATED = "users_user_created";
178
Dianne Hackborn4428e172012-08-24 17:43:05 -0700179 private final Context mContext;
180 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700182 // Short-term lock for internal state, when interaction/sync with PM is not required
183 private final Object mUsersLock = new Object();
184 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700185
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800186 private final Handler mHandler;
187
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188 private final File mUsersDir;
189 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700190
Makoto Onuki068c54a2015-10-13 14:34:03 -0700191 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800192 * User-related information that is used for persisting to flash. Only UserInfo is
193 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800194 */
Amith Yamasani12747872015-12-07 14:19:49 -0800195 private static class UserData {
196 // Basic user information and properties
197 UserInfo info;
198 // Account name used when there is a strong association between a user and an account
199 String account;
200 // Account information for seeding into a newly created user. This could also be
201 // used for login validation for an existing user, for updating their credentials.
202 // In the latter case, data may not need to be persisted as it is only valid for the
203 // current login session.
204 String seedAccountName;
205 String seedAccountType;
206 PersistableBundle seedAccountOptions;
207 // Whether to perist the seed account information to be available after a boot
208 boolean persistSeedData;
209
210 void clearSeedAccountData() {
211 seedAccountName = null;
212 seedAccountType = null;
213 seedAccountOptions = null;
214 persistSeedData = false;
215 }
216 }
217
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800218 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800219 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800220
221 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700222 * User restrictions set via UserManager. This doesn't include restrictions set by
223 * device owner / profile owners.
224 *
225 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
226 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
227 * maybe shared between {@link #mBaseUserRestrictions} and
228 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
229 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700230 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700231 */
232 @GuardedBy("mRestrictionsLock")
233 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
234
235 /**
236 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
237 * with device / profile owner restrictions. We'll initialize it lazily; use
238 * {@link #getEffectiveUserRestrictions} to access it.
239 *
240 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
241 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
242 * maybe shared between {@link #mBaseUserRestrictions} and
243 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
244 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700245 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700246 */
247 @GuardedBy("mRestrictionsLock")
248 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
249
Makoto Onuki4f160732015-10-27 17:15:38 -0700250 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800251 * User restrictions that have already been applied in
252 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
253 * that have changed since the last
254 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700255 */
256 @GuardedBy("mRestrictionsLock")
257 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
258
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800259 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800260 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
261 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800262 */
263 @GuardedBy("mRestrictionsLock")
264 private Bundle mDevicePolicyGlobalUserRestrictions;
265
266 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800267 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
268 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800269 */
270 @GuardedBy("mRestrictionsLock")
271 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
272
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800273 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530274 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800275
276 /**
277 * Set of user IDs being actively removed. Removed IDs linger in this set
278 * for several seconds to work around a VFS caching issue.
279 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700280 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800281 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700282
Fyodor Kupolov82402752015-10-28 14:54:51 -0700283 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700284 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800285 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700286 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700287 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700288
Jason Monk62062992014-05-06 09:55:28 -0400289 private IAppOpsService mAppOpsService;
290
Makoto Onuki068c54a2015-10-13 14:34:03 -0700291 private final LocalService mLocalService;
292
Makoto Onukie7927da2015-11-25 10:05:17 -0800293 @GuardedBy("mUsersLock")
294 private boolean mIsDeviceManaged;
295
296 @GuardedBy("mUsersLock")
297 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
298
Makoto Onukid45a4a22015-11-02 17:17:38 -0800299 @GuardedBy("mUserRestrictionsListeners")
300 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
301 new ArrayList<>();
302
Clara Bayarria1771112015-12-18 16:29:18 +0000303 private final LockPatternUtils mLockPatternUtils;
304
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100305 /**
306 * Whether all users should be created ephemeral.
307 */
308 @GuardedBy("mUsersLock")
309 private boolean mForceEphemeralUsers;
310
Amith Yamasani258848d2012-08-10 17:06:33 -0700311 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700312
Dianne Hackborn4428e172012-08-24 17:43:05 -0700313 public static UserManagerService getInstance() {
314 synchronized (UserManagerService.class) {
315 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700316 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700317 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700318
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800319 @VisibleForTesting
320 UserManagerService(File dataDir) {
321 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700322 }
323
Dianne Hackborn4428e172012-08-24 17:43:05 -0700324 /**
325 * Called by package manager to create the service. This is closely
326 * associated with the package manager, and the given lock is the
327 * package manager's own lock.
328 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800329 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
330 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700331 }
332
Dianne Hackborn4428e172012-08-24 17:43:05 -0700333 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800334 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700335 mContext = context;
336 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700337 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800338 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800339 synchronized (mPackagesLock) {
340 mUsersDir = new File(dataDir, USER_INFO_DIR);
341 mUsersDir.mkdirs();
342 // Make zeroth user directory, for services to migrate their files to that location
343 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
344 userZeroDir.mkdirs();
345 FileUtils.setPermissions(mUsersDir.toString(),
346 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
347 -1, -1);
348 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
349 initDefaultGuestRestrictions();
350 readUserListLP();
351 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700352 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700353 mLocalService = new LocalService();
354 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000355 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700356 }
357
358 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100359 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800360 ArrayList<UserInfo> partials = new ArrayList<>();
361 synchronized (mUsersLock) {
362 final int userSize = mUsers.size();
363 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800364 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100365 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800366 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700367 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700368 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700369 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800370 final int partialsSize = partials.size();
371 for (int i = 0; i < partialsSize; i++) {
372 UserInfo ui = partials.get(i);
373 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
374 + " (name=" + ui.name + ")");
375 removeUserState(ui.id);
376 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800377
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700378 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800379
Jason Monk62062992014-05-06 09:55:28 -0400380 mAppOpsService = IAppOpsService.Stub.asInterface(
381 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800382
383 synchronized (mRestrictionsLock) {
384 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400385 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700386 }
387
388 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800389 public String getUserAccount(int userId) {
390 checkManageUserAndAcrossUsersFullPermission("get user account");
391 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800392 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800393 }
394 }
395
396 @Override
397 public void setUserAccount(int userId, String accountName) {
398 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800399 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800400 synchronized (mPackagesLock) {
401 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800402 final UserData userData = mUsers.get(userId);
403 if (userData == null) {
404 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
405 return;
406 }
407 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800408 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800409 userData.account = accountName;
410 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800411 }
412 }
413
414 if (userToUpdate != null) {
415 writeUserLP(userToUpdate);
416 }
417 }
418 }
419
420 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700421 public UserInfo getPrimaryUser() {
422 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700423 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700424 final int userSize = mUsers.size();
425 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800426 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800427 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700428 return ui;
429 }
430 }
431 }
432 return null;
433 }
434
435 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700436 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700437 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700438 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700439 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700440 final int userSize = mUsers.size();
441 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800442 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700443 if (ui.partial) {
444 continue;
445 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800446 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700447 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700448 }
Amith Yamasani13593602012-03-22 16:16:17 -0700449 }
450 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700451 }
Amith Yamasani13593602012-03-22 16:16:17 -0700452 }
453
Amith Yamasani258848d2012-08-10 17:06:33 -0700454 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100455 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800456 if (userId != UserHandle.getCallingUserId()) {
457 checkManageUsersPermission("getting profiles related to user " + userId);
458 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700459 final long ident = Binder.clearCallingIdentity();
460 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700461 synchronized (mUsersLock) {
462 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100463 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700464 } finally {
465 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000466 }
467 }
468
Amith Yamasanibe465322014-04-24 13:45:17 -0700469 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700470 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
471 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700472 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700473 if (user == null) {
474 // Probably a dying user
475 return users;
476 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700477 final int userSize = mUsers.size();
478 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800479 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700480 if (!isProfileOf(user, profile)) {
481 continue;
482 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100483 if (enabledOnly && !profile.isEnabled()) {
484 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700485 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700486 if (mRemovingUserIds.get(profile.id)) {
487 continue;
488 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700489 users.add(profile);
490 }
491 return users;
492 }
493
Jessica Hummelbe81c802014-04-22 15:49:22 +0100494 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700495 public int getCredentialOwnerProfile(int userHandle) {
496 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000497 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700498 synchronized (mUsersLock) {
499 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700500 if (profileParent != null) {
501 return profileParent.id;
502 }
503 }
504 }
505
506 return userHandle;
507 }
508
509 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700510 public boolean isSameProfileGroup(int userId, int otherUserId) {
511 if (userId == otherUserId) return true;
512 checkManageUsersPermission("check if in the same profile group");
513 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700514 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700515 }
516 }
517
Fyodor Kupolov82402752015-10-28 14:54:51 -0700518 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
519 synchronized (mUsersLock) {
520 UserInfo userInfo = getUserInfoLU(userId);
521 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
522 return false;
523 }
524 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
525 if (otherUserInfo == null
526 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
527 return false;
528 }
529 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700530 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700531 }
532
533 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100534 public UserInfo getProfileParent(int userHandle) {
535 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700536 synchronized (mUsersLock) {
537 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700538 }
539 }
540
Fyodor Kupolov82402752015-10-28 14:54:51 -0700541 private UserInfo getProfileParentLU(int userHandle) {
542 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700543 if (profile == null) {
544 return null;
545 }
546 int parentUserId = profile.profileGroupId;
547 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
548 return null;
549 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700550 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100551 }
552 }
553
Fyodor Kupolov82402752015-10-28 14:54:51 -0700554 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100555 return user.id == profile.id ||
556 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
557 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000558 }
559
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000560 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000561 UserHandle parentHandle, boolean inQuietMode) {
562 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
563 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
564 intent.putExtra(Intent.EXTRA_USER, profileHandle);
565 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000566 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000567 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000568 }
569
570 @Override
571 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
572 checkManageUsersPermission("silence profile");
573 boolean changed = false;
574 UserInfo profile, parent;
575 synchronized (mPackagesLock) {
576 synchronized (mUsersLock) {
577 profile = getUserInfoLU(userHandle);
578 parent = getProfileParentLU(userHandle);
579
580 }
581 if (profile == null || !profile.isManagedProfile()) {
582 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
583 }
584 if (profile.isQuietModeEnabled() != enableQuietMode) {
585 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800586 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000587 changed = true;
588 }
589 }
590 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000591 long identity = Binder.clearCallingIdentity();
592 try {
593 if (enableQuietMode) {
594 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
595 } else {
596 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
597 }
598 } catch (RemoteException e) {
599 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
600 } finally {
601 Binder.restoreCallingIdentity(identity);
602 }
603
604 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
605 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000606 }
607 }
608
609 @Override
610 public boolean isQuietModeEnabled(int userHandle) {
611 synchronized (mPackagesLock) {
612 UserInfo info;
613 synchronized (mUsersLock) {
614 info = getUserInfoLU(userHandle);
615 }
616 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000617 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000618 }
619 return info.isQuietModeEnabled();
620 }
621 }
622
Kenny Guya52dc3e2014-02-11 15:33:14 +0000623 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100624 public void setUserEnabled(int userId) {
625 checkManageUsersPermission("enable user");
626 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700627 UserInfo info;
628 synchronized (mUsersLock) {
629 info = getUserInfoLU(userId);
630 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100631 if (info != null && !info.isEnabled()) {
632 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800633 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100634 }
635 }
636 }
637
638 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700639 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700640 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700641 synchronized (mUsersLock) {
642 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700643 }
644 }
645
Amith Yamasani71e6c692013-03-24 17:39:28 -0700646 @Override
647 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700648 synchronized (mUsersLock) {
649 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700650 }
651 }
652
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700653 @Override
654 public boolean canHaveRestrictedProfile(int userId) {
655 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700656 synchronized (mUsersLock) {
657 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700658 if (userInfo == null || !userInfo.canHaveProfile()) {
659 return false;
660 }
661 if (!userInfo.isAdmin()) {
662 return false;
663 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800664 // restricted profile can be created if there is no DO set and the admin user has no PO;
665 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700666 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700667 }
668
Amith Yamasani195263742012-08-21 15:40:12 -0700669 /*
670 * Should be locked on mUsers before calling this.
671 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700672 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800673 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700674 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800675 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700676 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
677 return null;
678 }
Amith Yamasani12747872015-12-07 14:19:49 -0800679 return userData != null ? userData.info : null;
680 }
681
682 private UserData getUserDataLU(int userId) {
683 final UserData userData = mUsers.get(userId);
684 // If it is partial and not in the process of being removed, return as unknown user.
685 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
686 return null;
687 }
688 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700689 }
690
Fyodor Kupolov82402752015-10-28 14:54:51 -0700691 /**
692 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
693 * <p>No permissions checking or any addition checks are made</p>
694 */
695 private UserInfo getUserInfoNoChecks(int userId) {
696 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800697 final UserData userData = mUsers.get(userId);
698 return userData != null ? userData.info : null;
699 }
700 }
701
702 /**
703 * Obtains {@link #mUsersLock} and return UserData from mUsers.
704 * <p>No permissions checking or any addition checks are made</p>
705 */
706 private UserData getUserDataNoChecks(int userId) {
707 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700708 return mUsers.get(userId);
709 }
710 }
711
Amith Yamasani236b2b52015-08-18 14:32:14 -0700712 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700713 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700714 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700715 }
716
Amith Yamasani258848d2012-08-10 17:06:33 -0700717 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700718 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700719 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700720 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700721 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800722 UserData userData = getUserDataNoChecks(userId);
723 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700724 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
725 return;
726 }
Amith Yamasani12747872015-12-07 14:19:49 -0800727 if (name != null && !name.equals(userData.info.name)) {
728 userData.info.name = name;
729 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700730 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700731 }
732 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700733 if (changed) {
734 sendUserInfoChangedBroadcast(userId);
735 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700736 }
737
Amith Yamasani258848d2012-08-10 17:06:33 -0700738 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700739 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700740 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100741 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
742 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
743 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700744 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100745 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700746 }
747
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100748
749
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700750 private void sendUserInfoChangedBroadcast(int userId) {
751 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
752 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
753 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700754 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700755 }
756
Amith Yamasani258848d2012-08-10 17:06:33 -0700757 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100758 public ParcelFileDescriptor getUserIcon(int userId) {
759 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700760 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700761 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700762 if (info == null || info.partial) {
763 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
764 return null;
765 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700766 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100767 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
768 || callingGroupId != info.profileGroupId) {
769 checkManageUsersPermission("get the icon of a user who is not related");
770 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700771 if (info.iconPath == null) {
772 return null;
773 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100774 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700775 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100776
777 try {
778 return ParcelFileDescriptor.open(
779 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
780 } catch (FileNotFoundException e) {
781 Log.e(LOG_TAG, "Couldn't find icon file", e);
782 }
783 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700784 }
785
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700786 public void makeInitialized(int userId) {
787 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800788 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800789 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800790 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800791 userData = mUsers.get(userId);
792 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700793 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800794 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700795 }
Amith Yamasani12747872015-12-07 14:19:49 -0800796 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
797 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800798 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700799 }
800 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800801 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800802 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800803 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700804 }
805
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700806 /**
807 * If default guest restrictions haven't been initialized yet, add the basic
808 * restrictions.
809 */
810 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800811 synchronized (mGuestRestrictions) {
812 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800813 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800814 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
815 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
816 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700817 }
818 }
819
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800820 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530821 public Bundle getDefaultGuestRestrictions() {
822 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800823 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530824 return new Bundle(mGuestRestrictions);
825 }
826 }
827
828 @Override
829 public void setDefaultGuestRestrictions(Bundle restrictions) {
830 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800831 synchronized (mGuestRestrictions) {
832 mGuestRestrictions.clear();
833 mGuestRestrictions.putAll(restrictions);
834 }
835 synchronized (mPackagesLock) {
836 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530837 }
838 }
839
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800840 /**
841 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
842 */
843 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
844 @Nullable Bundle global) {
845 Preconditions.checkNotNull(local);
846 boolean globalChanged = false;
847 boolean localChanged;
848 synchronized (mRestrictionsLock) {
849 if (global != null) {
850 // Update global.
851 globalChanged = !UserRestrictionsUtils.areEqual(
852 mDevicePolicyGlobalUserRestrictions, global);
853 if (globalChanged) {
854 mDevicePolicyGlobalUserRestrictions = global;
855 }
856 }
857 {
858 // Update local.
859 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
860 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
861 if (localChanged) {
862 mDevicePolicyLocalUserRestrictions.put(userId, local);
863 }
864 }
865 }
866 if (DBG) {
867 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
868 + " global=" + global + (globalChanged ? " (changed)" : "")
869 + " local=" + local + (localChanged ? " (changed)" : "")
870 );
871 }
872 // Don't call them within the mRestrictionsLock.
873 synchronized (mPackagesLock) {
874 if (globalChanged) {
875 writeUserListLP();
876 }
877 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800878 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800879 }
880 }
881
882 synchronized (mRestrictionsLock) {
883 if (globalChanged) {
884 applyUserRestrictionsForAllUsersLR();
885 } else if (localChanged) {
886 applyUserRestrictionsLR(userId);
887 }
888 }
889 }
890
Makoto Onuki068c54a2015-10-13 14:34:03 -0700891 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700892 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800893 final Bundle baseRestrictions =
894 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
895 final Bundle global = mDevicePolicyGlobalUserRestrictions;
896 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700897
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800898 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
899 // Common case first.
900 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700901 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800902 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
903 UserRestrictionsUtils.merge(effective, global);
904 UserRestrictionsUtils.merge(effective, local);
905
Makoto Onuki068c54a2015-10-13 14:34:03 -0700906 return effective;
907 }
908
909 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700910 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700911 if (DBG) {
912 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
913 }
914 mCachedEffectiveUserRestrictions.remove(userId);
915 }
916
917 private Bundle getEffectiveUserRestrictions(int userId) {
918 synchronized (mRestrictionsLock) {
919 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
920 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700921 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700922 mCachedEffectiveUserRestrictions.put(userId, restrictions);
923 }
924 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700925 }
926 }
927
Makoto Onuki068c54a2015-10-13 14:34:03 -0700928 /** @return a specific user restriction that's in effect currently. */
929 @Override
930 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800931 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
932 return false;
933 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700934 Bundle restrictions = getEffectiveUserRestrictions(userId);
935 return restrictions != null && restrictions.getBoolean(restrictionKey);
936 }
937
938 /**
939 * @return UserRestrictions that are in effect currently. This always returns a new
940 * {@link Bundle}.
941 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700942 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800943 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800944 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800945 }
946
947 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000948 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
949 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800950 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
951 return false;
952 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000953 synchronized (mRestrictionsLock) {
954 Bundle bundle = mBaseUserRestrictions.get(userId);
955 return (bundle != null && bundle.getBoolean(restrictionKey, false));
956 }
957 }
958
959 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700960 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700961 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800962 if (!UserRestrictionsUtils.isValidRestriction(key)) {
963 return;
964 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700965 synchronized (mRestrictionsLock) {
966 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
967 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800968 final Bundle newRestrictions = UserRestrictionsUtils.clone(
969 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700970 newRestrictions.putBoolean(key, value);
971
Fyodor Kupolov82402752015-10-28 14:54:51 -0700972 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700973 }
974 }
975
Makoto Onuki068c54a2015-10-13 14:34:03 -0700976 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800977 * Optionally updating user restrictions, calculate the effective user restrictions and also
978 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700979 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800980 * @param newRestrictions User restrictions to set.
981 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700982 * @param userId target user ID.
983 */
984 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700985 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700986 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800987
988 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
989 mAppliedUserRestrictions.get(userId));
990
991 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700992 if (newRestrictions != null) {
993 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800994 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
995
996 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700997 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
998 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800999
1000 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1001 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001002 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001003 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001004 }
1005
Fyodor Kupolov82402752015-10-28 14:54:51 -07001006 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001007
Makoto Onuki759a7632015-10-28 16:43:10 -07001008 mCachedEffectiveUserRestrictions.put(userId, effective);
1009
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001010 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001011 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001012 debug("Applying user restrictions: userId=" + userId
1013 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001014 }
1015
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001016 if (mAppOpsService != null) { // We skip it until system-ready.
1017 final long token = Binder.clearCallingIdentity();
1018 try {
1019 mAppOpsService.setUserRestrictions(effective, userId);
1020 } catch (RemoteException e) {
1021 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1022 } finally {
1023 Binder.restoreCallingIdentity(token);
1024 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001025 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001026
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001027 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001028
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001029 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001030 }
1031
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001032 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001033 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001034 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1035 // actually, but we still need some kind of synchronization otherwise we might end up
1036 // calling listeners out-of-order, thus "LR".
1037
1038 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1039 return;
1040 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001041
1042 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1043 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1044
1045 mHandler.post(new Runnable() {
1046 @Override
1047 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001048 UserRestrictionsUtils.applyUserRestrictions(
1049 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001050
Makoto Onukid45a4a22015-11-02 17:17:38 -08001051 final UserRestrictionsListener[] listeners;
1052 synchronized (mUserRestrictionsListeners) {
1053 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1054 mUserRestrictionsListeners.toArray(listeners);
1055 }
1056 for (int i = 0; i < listeners.length; i++) {
1057 listeners[i].onUserRestrictionsChanged(userId,
1058 newRestrictionsFinal, prevRestrictionsFinal);
1059 }
1060 }
1061 });
1062 }
1063
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001064 // Package private for the inner class.
1065 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001066 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001067 }
1068
1069 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001070 // Package private for the inner class.
1071 void applyUserRestrictionsForAllUsersLR() {
1072 if (DBG) {
1073 debug("applyUserRestrictionsForAllUsersLR");
1074 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001075 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001076 mCachedEffectiveUserRestrictions.clear();
1077
Makoto Onuki068c54a2015-10-13 14:34:03 -07001078 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1079 // it on a handler.
1080 final Runnable r = new Runnable() {
1081 @Override
1082 public void run() {
1083 // Then get the list of running users.
1084 final int[] runningUsers;
1085 try {
1086 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1087 } catch (RemoteException e) {
1088 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1089 return;
1090 }
1091 // Then re-calculate the effective restrictions and apply, only for running users.
1092 // It's okay if a new user has started after the getRunningUserIds() call,
1093 // because we'll do the same thing (re-calculate the restrictions and apply)
1094 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001095 synchronized (mRestrictionsLock) {
1096 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001097 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001098 }
1099 }
1100 }
1101 };
1102 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001103 }
1104
Amith Yamasani258848d2012-08-10 17:06:33 -07001105 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001106 * Check if we've hit the limit of how many users can be created.
1107 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001108 private boolean isUserLimitReached() {
1109 int count;
1110 synchronized (mUsersLock) {
1111 count = getAliveUsersExcludingGuestsCountLU();
1112 }
1113 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001114 }
1115
1116 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001117 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001118 checkManageUsersPermission("check if more managed profiles can be added.");
1119 if (ActivityManager.isLowRamDeviceStatic()) {
1120 return false;
1121 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001122 if (!mContext.getPackageManager().hasSystemFeature(
1123 PackageManager.FEATURE_MANAGED_USERS)) {
1124 return false;
1125 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001126 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001127 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1128 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1129 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001130 return false;
1131 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001132 synchronized(mUsersLock) {
1133 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001134 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001135 return false;
1136 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001137 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1138 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001139 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001140 return usersCountAfterRemoving == 1
1141 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001142 }
1143 }
1144
Fyodor Kupolov82402752015-10-28 14:54:51 -07001145 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001146 int aliveUserCount = 0;
1147 final int totalUserCount = mUsers.size();
1148 // Skip over users being removed
1149 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001150 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001151 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001152 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001153 aliveUserCount++;
1154 }
1155 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001156 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001157 }
1158
1159 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001160 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001161 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1162 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1163 * permissions can make certain calls to the UserManager.
1164 *
1165 * @param message used as message if SecurityException is thrown
1166 * @throws SecurityException if the caller does not have enough privilege.
1167 */
1168 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1169 final int uid = Binder.getCallingUid();
1170 if (uid != Process.SYSTEM_UID && uid != 0
1171 && ActivityManager.checkComponentPermission(
1172 Manifest.permission.MANAGE_USERS,
1173 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1174 && ActivityManager.checkComponentPermission(
1175 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1176 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1177 throw new SecurityException(
1178 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1179 + message);
1180 }
1181 }
1182
1183 /**
1184 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001185 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001186 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001187 *
1188 * @param message used as message if SecurityException is thrown
1189 * @throws SecurityException if the caller is not system or root
1190 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001191 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001192 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001193 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001194 && ActivityManager.checkComponentPermission(
1195 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001196 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1197 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1198 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001199 }
1200
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001201 /**
1202 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1203 * UserManager.
1204 *
1205 * @param message used as message if SecurityException is thrown
1206 * @throws SecurityException if the caller is not system or root
1207 */
1208 private static void checkSystemOrRoot(String message) {
1209 final int uid = Binder.getCallingUid();
1210 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1211 throw new SecurityException("Only system may: " + message);
1212 }
1213 }
1214
Fyodor Kupolov82402752015-10-28 14:54:51 -07001215 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001216 try {
1217 File dir = new File(mUsersDir, Integer.toString(info.id));
1218 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001219 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001220 if (!dir.exists()) {
1221 dir.mkdir();
1222 FileUtils.setPermissions(
1223 dir.getPath(),
1224 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1225 -1, -1);
1226 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001227 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001228 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1229 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001230 info.iconPath = file.getAbsolutePath();
1231 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001232 try {
1233 os.close();
1234 } catch (IOException ioe) {
1235 // What the ... !
1236 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001237 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001238 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001239 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001240 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001241 }
1242
Amith Yamasani0b285492011-04-14 17:35:23 -07001243 /**
1244 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1245 * cache it elsewhere.
1246 * @return the array of user ids.
1247 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001248 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001249 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001250 return mUserIds;
1251 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001252 }
1253
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001254 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001255 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001256 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001257 return;
1258 }
1259 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001260 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001261 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001262 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001263 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001264 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001265 int type;
1266 while ((type = parser.next()) != XmlPullParser.START_TAG
1267 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001268 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001269 }
1270
1271 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001272 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001273 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001274 return;
1275 }
1276
Amith Yamasani2a003292012-08-14 18:25:45 -07001277 mNextSerialNumber = -1;
1278 if (parser.getName().equals(TAG_USERS)) {
1279 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1280 if (lastSerialNumber != null) {
1281 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1282 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001283 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1284 if (versionNumber != null) {
1285 mUserVersion = Integer.parseInt(versionNumber);
1286 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001287 }
1288
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001289 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1290
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001291 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301292 if (type == XmlPullParser.START_TAG) {
1293 final String name = parser.getName();
1294 if (name.equals(TAG_USER)) {
1295 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001296
Amith Yamasani12747872015-12-07 14:19:49 -08001297 UserData userData = readUserLP(Integer.parseInt(id));
1298
1299 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001300 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001301 mUsers.put(userData.info.id, userData);
1302 if (mNextSerialNumber < 0
1303 || mNextSerialNumber <= userData.info.id) {
1304 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001305 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301306 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001307 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301308 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001309 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1310 && type != XmlPullParser.END_TAG) {
1311 if (type == XmlPullParser.START_TAG) {
1312 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001313 synchronized (mGuestRestrictions) {
1314 UserRestrictionsUtils
1315 .readRestrictions(parser, mGuestRestrictions);
1316 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001317 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1318 ) {
1319 UserRestrictionsUtils.readRestrictions(parser,
1320 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001321 }
1322 break;
1323 }
1324 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001325 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001326 }
1327 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001328 synchronized (mRestrictionsLock) {
1329 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1330 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001331 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001332 upgradeIfNecessaryLP();
1333 } catch (IOException | XmlPullParserException e) {
1334 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001335 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001336 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001337 }
1338 }
1339
Amith Yamasani6f34b412012-10-22 18:19:27 -07001340 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001341 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001342 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001343 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001344 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001345 int userVersion = mUserVersion;
1346 if (userVersion < 1) {
1347 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001348 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1349 if ("Primary".equals(userData.info.name)) {
1350 userData.info.name =
1351 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1352 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001353 }
1354 userVersion = 1;
1355 }
1356
Amith Yamasanibc9625052012-11-15 14:39:18 -08001357 if (userVersion < 2) {
1358 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001359 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1360 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1361 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1362 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001363 }
1364 userVersion = 2;
1365 }
1366
Amith Yamasani350962c2013-08-06 11:18:53 -07001367
Amith Yamasani5e486f52013-08-07 11:06:44 -07001368 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001369 userVersion = 4;
1370 }
1371
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001372 if (userVersion < 5) {
1373 initDefaultGuestRestrictions();
1374 userVersion = 5;
1375 }
1376
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001377 if (userVersion < 6) {
1378 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001379 synchronized (mUsersLock) {
1380 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001381 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001382 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001383 if (!splitSystemUser && userData.info.isRestricted()
1384 && (userData.info.restrictedProfileParentId
1385 == UserInfo.NO_PROFILE_GROUP_ID)) {
1386 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1387 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001388 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001389 }
1390 }
1391 userVersion = 6;
1392 }
1393
Amith Yamasani6f34b412012-10-22 18:19:27 -07001394 if (userVersion < USER_VERSION) {
1395 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1396 + USER_VERSION);
1397 } else {
1398 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001399
1400 if (originalVersion < mUserVersion) {
1401 writeUserListLP();
1402 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001403 }
1404 }
1405
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001406 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001407 int flags = UserInfo.FLAG_INITIALIZED;
1408 // In split system user mode, the admin and primary flags are assigned to the first human
1409 // user.
1410 if (!UserManager.isSplitSystemUser()) {
1411 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1412 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001413 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001414 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001415 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001416 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001417 UserData userData = new UserData();
1418 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001419 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001420 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001421 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001422 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001423 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001424
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001425 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001426 synchronized (mRestrictionsLock) {
1427 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1428 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001429
Fyodor Kupolov82402752015-10-28 14:54:51 -07001430 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001431 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001432
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001433 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001434 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001435 }
1436
Amith Yamasani12747872015-12-07 14:19:49 -08001437 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001438 if (DBG) {
1439 debug("scheduleWriteUser");
1440 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001441 // No need to wrap it within a lock -- worst case, we'll just post the same message
1442 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001443 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1444 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001445 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1446 }
1447 }
1448
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001449 /*
1450 * Writes the user file in this format:
1451 *
1452 * <user flags="20039023" id="0">
1453 * <name>Primary</name>
1454 * </user>
1455 */
Amith Yamasani12747872015-12-07 14:19:49 -08001456 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001457 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001458 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001459 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001460 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001461 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001462 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001463 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001464 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1465
1466 // XmlSerializer serializer = XmlUtils.serializerInstance();
1467 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001468 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001469 serializer.startDocument(null, true);
1470 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1471
Amith Yamasani12747872015-12-07 14:19:49 -08001472 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001473 serializer.startTag(null, TAG_USER);
1474 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001475 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001476 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001477 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1478 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1479 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001480 if (userInfo.iconPath != null) {
1481 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1482 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001483 if (userInfo.partial) {
1484 serializer.attribute(null, ATTR_PARTIAL, "true");
1485 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001486 if (userInfo.guestToRemove) {
1487 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1488 }
Kenny Guy2a764942014-04-02 13:29:20 +01001489 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1490 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1491 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001492 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001493 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1494 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1495 Integer.toString(userInfo.restrictedProfileParentId));
1496 }
Amith Yamasani12747872015-12-07 14:19:49 -08001497 // Write seed data
1498 if (userData.persistSeedData) {
1499 if (userData.seedAccountName != null) {
1500 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1501 }
1502 if (userData.seedAccountType != null) {
1503 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1504 }
1505 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001506 serializer.startTag(null, TAG_NAME);
1507 serializer.text(userInfo.name);
1508 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001509 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001510 UserRestrictionsUtils.writeRestrictions(serializer,
1511 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1512 UserRestrictionsUtils.writeRestrictions(serializer,
1513 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1514 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001515 }
Amith Yamasani12747872015-12-07 14:19:49 -08001516
1517 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001518 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001519 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001520 serializer.endTag(null, TAG_ACCOUNT);
1521 }
1522
Amith Yamasani12747872015-12-07 14:19:49 -08001523 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1524 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1525 userData.seedAccountOptions.saveToXml(serializer);
1526 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1527 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001528 serializer.endTag(null, TAG_USER);
1529
1530 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001531 userFile.finishWrite(fos);
1532 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001533 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001534 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001535 }
1536 }
1537
1538 /*
1539 * Writes the user list file in this format:
1540 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001541 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001542 * <user id="0"></user>
1543 * <user id="2"></user>
1544 * </users>
1545 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001546 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001547 if (DBG) {
1548 debug("writeUserList");
1549 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001550 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001551 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001552 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001553 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001554 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1555
1556 // XmlSerializer serializer = XmlUtils.serializerInstance();
1557 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001558 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001559 serializer.startDocument(null, true);
1560 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1561
1562 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001563 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001564 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001565
Adam Lesinskieddeb492014-09-08 17:50:03 -07001566 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001567 synchronized (mGuestRestrictions) {
1568 UserRestrictionsUtils
1569 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1570 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301571 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001572 synchronized (mRestrictionsLock) {
1573 UserRestrictionsUtils.writeRestrictions(serializer,
1574 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1575 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001576 int[] userIdsToWrite;
1577 synchronized (mUsersLock) {
1578 userIdsToWrite = new int[mUsers.size()];
1579 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001580 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001581 userIdsToWrite[i] = user.id;
1582 }
1583 }
1584 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001585 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001586 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001587 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001588 }
1589
1590 serializer.endTag(null, TAG_USERS);
1591
1592 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001593 userListFile.finishWrite(fos);
1594 } catch (Exception e) {
1595 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001596 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001597 }
1598 }
1599
Amith Yamasani12747872015-12-07 14:19:49 -08001600 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001601 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001602 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001603 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001604 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001605 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001606 long creationTime = 0L;
1607 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001608 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001609 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001610 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001611 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001612 boolean persistSeedData = false;
1613 String seedAccountName = null;
1614 String seedAccountType = null;
1615 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001616 Bundle baseRestrictions = new Bundle();
1617 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001618
1619 FileInputStream fis = null;
1620 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001621 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001622 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001623 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001624 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001625 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001626 int type;
1627 while ((type = parser.next()) != XmlPullParser.START_TAG
1628 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001629 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001630 }
1631
1632 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001633 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001634 return null;
1635 }
1636
1637 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001638 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1639 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001640 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001641 return null;
1642 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001643 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1644 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001645 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001646 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1647 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001648 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1649 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001650 restrictedProfileParentId = readIntAttribute(parser,
1651 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001652 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1653 if ("true".equals(valueString)) {
1654 partial = true;
1655 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001656 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1657 if ("true".equals(valueString)) {
1658 guestToRemove = true;
1659 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001660
Amith Yamasani12747872015-12-07 14:19:49 -08001661 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1662 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1663 if (seedAccountName != null || seedAccountType != null) {
1664 persistSeedData = true;
1665 }
1666
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001667 int outerDepth = parser.getDepth();
1668 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1669 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1670 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1671 continue;
1672 }
1673 String tag = parser.getName();
1674 if (TAG_NAME.equals(tag)) {
1675 type = parser.next();
1676 if (type == XmlPullParser.TEXT) {
1677 name = parser.getText();
1678 }
1679 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001680 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1681 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1682 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001683 } else if (TAG_ACCOUNT.equals(tag)) {
1684 type = parser.next();
1685 if (type == XmlPullParser.TEXT) {
1686 account = parser.getText();
1687 }
Amith Yamasani12747872015-12-07 14:19:49 -08001688 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1689 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1690 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001691 }
1692 }
1693 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001694
Amith Yamasani12747872015-12-07 14:19:49 -08001695 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001696 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001697 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001698 userInfo.creationTime = creationTime;
1699 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001700 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001701 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001702 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001703 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001704
1705 // Create the UserData object that's internal to this class
1706 UserData userData = new UserData();
1707 userData.info = userInfo;
1708 userData.account = account;
1709 userData.seedAccountName = seedAccountName;
1710 userData.seedAccountType = seedAccountType;
1711 userData.persistSeedData = persistSeedData;
1712 userData.seedAccountOptions = seedAccountOptions;
1713
Makoto Onuki068c54a2015-10-13 14:34:03 -07001714 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001715 mBaseUserRestrictions.put(id, baseRestrictions);
1716 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001717 }
Amith Yamasani12747872015-12-07 14:19:49 -08001718 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001719 } catch (IOException ioe) {
1720 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001721 } finally {
1722 if (fis != null) {
1723 try {
1724 fis.close();
1725 } catch (IOException e) {
1726 }
1727 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001728 }
1729 return null;
1730 }
1731
Amith Yamasani920ace02012-09-20 22:15:37 -07001732 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1733 String valueString = parser.getAttributeValue(null, attr);
1734 if (valueString == null) return defaultValue;
1735 try {
1736 return Integer.parseInt(valueString);
1737 } catch (NumberFormatException nfe) {
1738 return defaultValue;
1739 }
1740 }
1741
1742 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1743 String valueString = parser.getAttributeValue(null, attr);
1744 if (valueString == null) return defaultValue;
1745 try {
1746 return Long.parseLong(valueString);
1747 } catch (NumberFormatException nfe) {
1748 return defaultValue;
1749 }
1750 }
1751
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001752 private boolean isPackageInstalled(String pkg, int userId) {
1753 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1754 PackageManager.GET_UNINSTALLED_PACKAGES,
1755 userId);
1756 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1757 return false;
1758 }
1759 return true;
1760 }
1761
Amith Yamasanib82add22013-07-09 11:24:44 -07001762 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001763 * Removes the app restrictions file for a specific package and user id, if it exists.
1764 */
1765 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1766 synchronized (mPackagesLock) {
1767 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001768 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001769 if (resFile.exists()) {
1770 resFile.delete();
1771 }
1772 }
1773 }
1774
Kenny Guya52dc3e2014-02-11 15:33:14 +00001775 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001776 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001777 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001778 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001779 }
1780
Amith Yamasani258848d2012-08-10 17:06:33 -07001781 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001782 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001783 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001784 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001785 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001786
Jessica Hummelbe81c802014-04-22 15:49:22 +01001787 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001788 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001789 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1790 return null;
1791 }
phweisse9c44062016-02-10 12:57:38 +01001792 return createUserInternalUnchecked(name, flags, parentId);
1793 }
1794
1795 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001796 if (ActivityManager.isLowRamDeviceStatic()) {
1797 return null;
1798 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001799 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001800 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001801 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001802 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001803 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001804 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001805 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001806 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001807 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001808 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001809 if (parentId != UserHandle.USER_NULL) {
1810 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001811 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001812 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001813 if (parent == null) return null;
1814 }
1815 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1816 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1817 return null;
1818 }
1819 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1820 // If we're not adding a guest user or a managed profile and the limit has
1821 // been reached, cannot add a user.
1822 return null;
1823 }
1824 // If we're adding a guest and there already exists one, bail.
1825 if (isGuest && findCurrentGuestUser() != null) {
1826 return null;
1827 }
1828 // In legacy mode, restricted profile's parent can only be the owner user
1829 if (isRestricted && !UserManager.isSplitSystemUser()
1830 && (parentId != UserHandle.USER_SYSTEM)) {
1831 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1832 return null;
1833 }
1834 if (isRestricted && UserManager.isSplitSystemUser()) {
1835 if (parent == null) {
1836 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1837 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001838 return null;
1839 }
Amith Yamasani12747872015-12-07 14:19:49 -08001840 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001841 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1842 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001843 return null;
1844 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001845 }
1846 // In split system user mode, we assign the first human user the primary flag.
1847 // And if there is no device owner, we also assign the admin flag to primary user.
1848 if (UserManager.isSplitSystemUser()
1849 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1850 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001851 synchronized (mUsersLock) {
1852 if (!mIsDeviceManaged) {
1853 flags |= UserInfo.FLAG_ADMIN;
1854 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001855 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001856 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001857
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001858 userId = getNextAvailableId();
1859 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001860 boolean ephemeralGuests = Resources.getSystem()
1861 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001862
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001863 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001864 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1865 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1866 || (parent != null && parent.info.isEphemeral())) {
1867 flags |= UserInfo.FLAG_EPHEMERAL;
1868 }
1869
1870 userInfo = new UserInfo(userId, name, null, flags);
1871 userInfo.serialNumber = mNextSerialNumber++;
1872 long now = System.currentTimeMillis();
1873 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1874 userInfo.partial = true;
1875 userData = new UserData();
1876 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001877 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001878 }
1879 writeUserListLP();
1880 if (parent != null) {
1881 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001882 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1883 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001884 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001885 }
Amith Yamasani12747872015-12-07 14:19:49 -08001886 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001887 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001888 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1889 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001890 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001891 }
Amith Yamasani12747872015-12-07 14:19:49 -08001892 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001893 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001894 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001895 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001896 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001897 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkey47f71082016-02-01 17:03:54 -07001898 prepareUserStorage(userId, userInfo.serialNumber,
1899 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001900 mPm.createNewUser(userId);
1901 userInfo.partial = false;
1902 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001903 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001904 }
1905 updateUserIds();
1906 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001907 if (isGuest) {
1908 synchronized (mGuestRestrictions) {
1909 restrictions.putAll(mGuestRestrictions);
1910 }
1911 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001912 synchronized (mRestrictionsLock) {
1913 mBaseUserRestrictions.append(userId, restrictions);
1914 }
1915 mPm.newUserCreated(userId);
1916 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1917 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1918 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1919 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001920 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001921 } finally {
1922 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001923 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001924 return userInfo;
1925 }
1926
Amith Yamasani0b285492011-04-14 17:35:23 -07001927 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001928 * @hide
1929 */
Amith Yamasani12747872015-12-07 14:19:49 -08001930 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001931 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1932 checkManageUsersPermission("setupRestrictedProfile");
1933 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1934 if (user == null) {
1935 return null;
1936 }
1937 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1938 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1939 // the putIntForUser() will fail.
1940 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1941 android.provider.Settings.Secure.LOCATION_MODE,
1942 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1943 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1944 return user;
1945 }
1946
1947 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001948 * Find the current guest user. If the Guest user is partial,
1949 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001950 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001951 private UserInfo findCurrentGuestUser() {
1952 synchronized (mUsersLock) {
1953 final int size = mUsers.size();
1954 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001955 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001956 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1957 return user;
1958 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001959 }
1960 }
1961 return null;
1962 }
1963
1964 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001965 * Mark this guest user for deletion to allow us to create another guest
1966 * and switch to that user before actually removing this guest.
1967 * @param userHandle the userid of the current guest
1968 * @return whether the user could be marked for deletion
1969 */
Amith Yamasani12747872015-12-07 14:19:49 -08001970 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07001971 public boolean markGuestForDeletion(int userHandle) {
1972 checkManageUsersPermission("Only the system can remove users");
1973 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1974 UserManager.DISALLOW_REMOVE_USER, false)) {
1975 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1976 return false;
1977 }
1978
1979 long ident = Binder.clearCallingIdentity();
1980 try {
Amith Yamasani12747872015-12-07 14:19:49 -08001981 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07001982 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001983 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001984 userData = mUsers.get(userHandle);
1985 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001986 return false;
1987 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001988 }
Amith Yamasani12747872015-12-07 14:19:49 -08001989 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07001990 return false;
1991 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001992 // We set this to a guest user that is to be removed. This is a temporary state
1993 // where we are allowed to add new Guest users, even if this one is still not
1994 // removed. This user will still show up in getUserInfo() calls.
1995 // If we don't get around to removing this Guest user, it will be purged on next
1996 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08001997 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001998 // Mark it as disabled, so that it isn't returned any more when
1999 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002000 userData.info.flags |= UserInfo.FLAG_DISABLED;
2001 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002002 }
2003 } finally {
2004 Binder.restoreCallingIdentity(ident);
2005 }
2006 return true;
2007 }
2008
2009 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002010 * Removes a user and all data directories created for that user. This method should be called
2011 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002012 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002013 */
Amith Yamasani12747872015-12-07 14:19:49 -08002014 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002015 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002016 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002017 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2018 UserManager.DISALLOW_REMOVE_USER, false)) {
2019 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2020 return false;
2021 }
2022
Kenny Guyee58b4f2014-05-23 15:19:53 +01002023 long ident = Binder.clearCallingIdentity();
2024 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002025 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002026 int currentUser = ActivityManager.getCurrentUser();
2027 if (currentUser == userHandle) {
2028 Log.w(LOG_TAG, "Current user cannot be removed");
2029 return false;
2030 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002031 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002032 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002033 userData = mUsers.get(userHandle);
2034 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002035 return false;
2036 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002037
Fyodor Kupolov82402752015-10-28 14:54:51 -07002038 // We remember deleted user IDs to prevent them from being
2039 // reused during the current boot; they can still be reused
2040 // after a reboot.
2041 mRemovingUserIds.put(userHandle, true);
2042 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002043
Kenny Guyee58b4f2014-05-23 15:19:53 +01002044 try {
2045 mAppOpsService.removeUser(userHandle);
2046 } catch (RemoteException e) {
2047 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2048 }
2049 // Set this to a partially created user, so that the user will be purged
2050 // on next startup, in case the runtime stops now before stopping and
2051 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002052 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002053 // Mark it as disabled, so that it isn't returned any more when
2054 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002055 userData.info.flags |= UserInfo.FLAG_DISABLED;
2056 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002057 }
2058
Amith Yamasani12747872015-12-07 14:19:49 -08002059 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2060 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002061 // Send broadcast to notify system that the user removed was a
2062 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002063 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002064 }
2065
2066 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2067 int res;
2068 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002069 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2070 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002071 @Override
2072 public void userStopped(int userId) {
2073 finishRemoveUser(userId);
2074 }
2075 @Override
2076 public void userStopAborted(int userId) {
2077 }
2078 });
2079 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002080 return false;
2081 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002082 return res == ActivityManager.USER_OP_SUCCESS;
2083 } finally {
2084 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002085 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002086 }
2087
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002088 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002089 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002090 // Let other services shutdown any activity and clean up their state before completely
2091 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002092 long ident = Binder.clearCallingIdentity();
2093 try {
2094 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2095 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002096 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2097 android.Manifest.permission.MANAGE_USERS,
2098
2099 new BroadcastReceiver() {
2100 @Override
2101 public void onReceive(Context context, Intent intent) {
2102 if (DBG) {
2103 Slog.i(LOG_TAG,
2104 "USER_REMOVED broadcast sent, cleaning up user data "
2105 + userHandle);
2106 }
2107 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002108 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002109 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002110 // Clean up any ActivityManager state
2111 LocalServices.getService(ActivityManagerInternal.class)
2112 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002113 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002114 }
2115 }.start();
2116 }
2117 },
2118
2119 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002120 } finally {
2121 Binder.restoreCallingIdentity(ident);
2122 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002123 }
2124
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002125 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002126 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002127 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002128 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002129
2130 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002131 synchronized (mUsersLock) {
2132 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002133 mIsUserManaged.delete(userHandle);
2134 }
2135 synchronized (mRestrictionsLock) {
2136 mBaseUserRestrictions.remove(userHandle);
2137 mAppliedUserRestrictions.remove(userHandle);
2138 mCachedEffectiveUserRestrictions.remove(userHandle);
2139 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002140 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002141 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002142 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002143 userFile.delete();
2144 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002145 synchronized (mPackagesLock) {
2146 writeUserListLP();
2147 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002148 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002149 File userDir = Environment.getUserSystemDirectory(userHandle);
2150 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2151 if (userDir.renameTo(renamedUserDir)) {
2152 removeDirectoryRecursive(renamedUserDir);
2153 } else {
2154 removeDirectoryRecursive(userDir);
2155 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002156 }
2157
Amith Yamasani61f57372012-08-31 12:12:28 -07002158 private void removeDirectoryRecursive(File parent) {
2159 if (parent.isDirectory()) {
2160 String[] files = parent.list();
2161 for (String filename : files) {
2162 File child = new File(parent, filename);
2163 removeDirectoryRecursive(child);
2164 }
2165 }
2166 parent.delete();
2167 }
2168
Kenny Guyf8d3a232014-05-15 16:09:52 +01002169 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002170 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002171 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2172 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002173 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002174 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002175 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002176 }
2177
Amith Yamasani2a003292012-08-14 18:25:45 -07002178 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002179 public Bundle getApplicationRestrictions(String packageName) {
2180 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2181 }
2182
2183 @Override
2184 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002185 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002186 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002187 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002188 }
2189 synchronized (mPackagesLock) {
2190 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002191 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002192 }
2193 }
2194
2195 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002196 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002197 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002198 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002199 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002200 if (restrictions == null || restrictions.isEmpty()) {
2201 cleanAppRestrictionsForPackage(packageName, userId);
2202 } else {
2203 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002204 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002205 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002206 }
Robin Lee66e5d962014-04-09 16:44:21 +01002207
Kenny Guyd21b2182014-07-17 16:38:55 +01002208 if (isPackageInstalled(packageName, userId)) {
2209 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2210 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2211 changeIntent.setPackage(packageName);
2212 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2213 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2214 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002215 }
2216
2217 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002218 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002219 try {
2220 return mContext.getPackageManager().getApplicationInfo(packageName,
2221 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2222 } catch (NameNotFoundException nnfe) {
2223 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002224 } finally {
2225 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002226 }
2227 }
2228
Fyodor Kupolov82402752015-10-28 14:54:51 -07002229 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002230 AtomicFile restrictionsFile =
2231 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2232 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002233 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002234 }
2235
2236 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002237 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002238 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002239 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002240 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002241 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002242 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002243
2244 FileInputStream fis = null;
2245 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002246 fis = restrictionsFile.openRead();
2247 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002248 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002249 XmlUtils.nextElement(parser);
2250 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002251 Slog.e(LOG_TAG, "Unable to read restrictions file "
2252 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002253 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002254 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002255 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2256 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002257 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002258 } catch (IOException|XmlPullParserException e) {
2259 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002260 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002261 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002262 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002263 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002264 }
2265
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002266 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2267 XmlPullParser parser) throws XmlPullParserException, IOException {
2268 int type = parser.getEventType();
2269 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2270 String key = parser.getAttributeValue(null, ATTR_KEY);
2271 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2272 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2273 if (multiple != null) {
2274 values.clear();
2275 int count = Integer.parseInt(multiple);
2276 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2277 if (type == XmlPullParser.START_TAG
2278 && parser.getName().equals(TAG_VALUE)) {
2279 values.add(parser.nextText().trim());
2280 count--;
2281 }
2282 }
2283 String [] valueStrings = new String[values.size()];
2284 values.toArray(valueStrings);
2285 restrictions.putStringArray(key, valueStrings);
2286 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2287 restrictions.putBundle(key, readBundleEntry(parser, values));
2288 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2289 final int outerDepth = parser.getDepth();
2290 ArrayList<Bundle> bundleList = new ArrayList<>();
2291 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2292 Bundle childBundle = readBundleEntry(parser, values);
2293 bundleList.add(childBundle);
2294 }
2295 restrictions.putParcelableArray(key,
2296 bundleList.toArray(new Bundle[bundleList.size()]));
2297 } else {
2298 String value = parser.nextText().trim();
2299 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2300 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2301 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2302 restrictions.putInt(key, Integer.parseInt(value));
2303 } else {
2304 restrictions.putString(key, value);
2305 }
2306 }
2307 }
2308 }
2309
2310 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2311 throws IOException, XmlPullParserException {
2312 Bundle childBundle = new Bundle();
2313 final int outerDepth = parser.getDepth();
2314 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2315 readEntry(childBundle, values, parser);
2316 }
2317 return childBundle;
2318 }
2319
Fyodor Kupolov82402752015-10-28 14:54:51 -07002320 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002321 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002322 AtomicFile restrictionsFile = new AtomicFile(
2323 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002324 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002325 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002326 }
2327
2328 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002329 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002330 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002331 try {
2332 fos = restrictionsFile.startWrite();
2333 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2334
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002335 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002336 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002337 serializer.startDocument(null, true);
2338 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2339
2340 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002341 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002342 serializer.endTag(null, TAG_RESTRICTIONS);
2343
2344 serializer.endDocument();
2345 restrictionsFile.finishWrite(fos);
2346 } catch (Exception e) {
2347 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002348 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2349 }
2350 }
2351
2352 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2353 throws IOException {
2354 for (String key : restrictions.keySet()) {
2355 Object value = restrictions.get(key);
2356 serializer.startTag(null, TAG_ENTRY);
2357 serializer.attribute(null, ATTR_KEY, key);
2358
2359 if (value instanceof Boolean) {
2360 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2361 serializer.text(value.toString());
2362 } else if (value instanceof Integer) {
2363 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2364 serializer.text(value.toString());
2365 } else if (value == null || value instanceof String) {
2366 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2367 serializer.text(value != null ? (String) value : "");
2368 } else if (value instanceof Bundle) {
2369 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2370 writeBundle((Bundle) value, serializer);
2371 } else if (value instanceof Parcelable[]) {
2372 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2373 Parcelable[] array = (Parcelable[]) value;
2374 for (Parcelable parcelable : array) {
2375 if (!(parcelable instanceof Bundle)) {
2376 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2377 }
2378 serializer.startTag(null, TAG_ENTRY);
2379 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2380 writeBundle((Bundle) parcelable, serializer);
2381 serializer.endTag(null, TAG_ENTRY);
2382 }
2383 } else {
2384 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2385 String[] values = (String[]) value;
2386 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2387 for (String choice : values) {
2388 serializer.startTag(null, TAG_VALUE);
2389 serializer.text(choice != null ? choice : "");
2390 serializer.endTag(null, TAG_VALUE);
2391 }
2392 }
2393 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002394 }
2395 }
2396
2397 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002398 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002399 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002400 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002401 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002402 }
2403 }
2404
2405 @Override
2406 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002407 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002408 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002409 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002410 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002411 }
2412 // Not found
2413 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002414 }
2415 }
2416
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002417 @Override
2418 public long getUserCreationTime(int userHandle) {
2419 int callingUserId = UserHandle.getCallingUserId();
2420 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002421 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002422 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002423 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002424 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002425 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002426 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002427 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002428 }
2429 }
2430 }
2431 if (userInfo == null) {
2432 throw new SecurityException("userHandle can only be the calling user or a managed "
2433 + "profile associated with this user");
2434 }
2435 return userInfo.creationTime;
2436 }
2437
Amith Yamasani0b285492011-04-14 17:35:23 -07002438 /**
2439 * Caches the list of user ids in an array, adjusting the array size when necessary.
2440 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002441 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002442 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002443 synchronized (mUsersLock) {
2444 final int userSize = mUsers.size();
2445 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002446 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002447 num++;
2448 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002449 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002450 final int[] newUsers = new int[num];
2451 int n = 0;
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 newUsers[n++] = mUsers.keyAt(i);
2455 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002456 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002457 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002458 }
2459 }
2460
2461 /**
Jeff Sharkey47f71082016-02-01 17:03:54 -07002462 * Prepare storage areas for given user on all mounted devices.
2463 */
2464 private void prepareUserStorage(int userId, int userSerial, int flags) {
2465 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2466 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
2467 final String volumeUuid = vol.getFsUuid();
2468 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
2469 }
2470 }
2471
2472 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002473 * Called right before a user is started. This gives us a chance to prepare
2474 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002475 */
2476 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002477 final int userSerial = getUserSerialNumber(userId);
2478 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2479 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002480
2481 if (userId != UserHandle.USER_SYSTEM) {
2482 synchronized (mRestrictionsLock) {
2483 applyUserRestrictionsLR(userId);
2484 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002485 }
2486 }
2487
2488 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002489 * Called right before a user is unlocked. This gives us a chance to prepare
2490 * app storage.
2491 */
2492 public void onBeforeUnlockUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002493 final int userSerial = getUserSerialNumber(userId);
2494 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
2495 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002496 }
2497
2498 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002499 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002500 * @param userId the user that was just foregrounded
2501 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002502 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002503 UserData userData = getUserDataNoChecks(userId);
2504 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002505 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2506 return;
2507 }
2508 long now = System.currentTimeMillis();
2509 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002510 userData.info.lastLoggedInTime = now;
2511 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002512 }
2513 }
2514
2515 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002516 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002517 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2518 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002519 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002520 private int getNextAvailableId() {
2521 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002522 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002523 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002524 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002525 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002526 }
2527 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002528 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002529 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002530 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002531 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002532
Amith Yamasanifc95e702013-09-26 13:20:17 -07002533 private String packageToRestrictionsFileName(String packageName) {
2534 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2535 }
2536
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002537 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002538 * Enforce that serial number stored in user directory inode matches the
2539 * given expected value. Gracefully sets the serial number if currently
2540 * undefined.
2541 *
2542 * @throws IOException when problem extracting serial number, or serial
2543 * number is mismatched.
2544 */
2545 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2546 final int foundSerial = getSerialNumber(file);
2547 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2548
2549 if (foundSerial == -1) {
2550 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2551 try {
2552 setSerialNumber(file, serialNumber);
2553 } catch (IOException e) {
2554 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2555 }
2556
2557 } else if (foundSerial != serialNumber) {
2558 throw new IOException("Found serial number " + foundSerial
2559 + " doesn't match expected " + serialNumber);
2560 }
2561 }
2562
2563 /**
2564 * Set serial number stored in user directory inode.
2565 *
2566 * @throws IOException if serial number was already set
2567 */
2568 private static void setSerialNumber(File file, int serialNumber)
2569 throws IOException {
2570 try {
2571 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2572 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2573 } catch (ErrnoException e) {
2574 throw e.rethrowAsIOException();
2575 }
2576 }
2577
2578 /**
2579 * Return serial number stored in user directory inode.
2580 *
2581 * @return parsed serial number, or -1 if not set
2582 */
2583 private static int getSerialNumber(File file) throws IOException {
2584 try {
2585 final byte[] buf = new byte[256];
2586 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2587 final String serial = new String(buf, 0, len);
2588 try {
2589 return Integer.parseInt(serial);
2590 } catch (NumberFormatException e) {
2591 throw new IOException("Bad serial number: " + serial);
2592 }
2593 } catch (ErrnoException e) {
2594 if (e.errno == OsConstants.ENODATA) {
2595 return -1;
2596 } else {
2597 throw e.rethrowAsIOException();
2598 }
2599 }
2600 }
2601
Amith Yamasani920ace02012-09-20 22:15:37 -07002602 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002603 public void setSeedAccountData(int userId, String accountName, String accountType,
2604 PersistableBundle accountOptions, boolean persist) {
2605 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2606 synchronized (mPackagesLock) {
2607 final UserData userData;
2608 synchronized (mUsersLock) {
2609 userData = getUserDataLU(userId);
2610 if (userData == null) {
2611 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2612 return;
2613 }
2614 userData.seedAccountName = accountName;
2615 userData.seedAccountType = accountType;
2616 userData.seedAccountOptions = accountOptions;
2617 userData.persistSeedData = persist;
2618 }
2619 if (persist) {
2620 writeUserLP(userData);
2621 }
2622 }
2623 }
2624
2625 @Override
2626 public String getSeedAccountName() throws RemoteException {
2627 checkManageUsersPermission("Cannot get seed account information");
2628 synchronized (mUsersLock) {
2629 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2630 return userData.seedAccountName;
2631 }
2632 }
2633
2634 @Override
2635 public String getSeedAccountType() throws RemoteException {
2636 checkManageUsersPermission("Cannot get seed account information");
2637 synchronized (mUsersLock) {
2638 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2639 return userData.seedAccountType;
2640 }
2641 }
2642
2643 @Override
2644 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2645 checkManageUsersPermission("Cannot get seed account information");
2646 synchronized (mUsersLock) {
2647 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2648 return userData.seedAccountOptions;
2649 }
2650 }
2651
2652 @Override
2653 public void clearSeedAccountData() throws RemoteException {
2654 checkManageUsersPermission("Cannot clear seed account information");
2655 synchronized (mPackagesLock) {
2656 UserData userData;
2657 synchronized (mUsersLock) {
2658 userData = getUserDataLU(UserHandle.getCallingUserId());
2659 if (userData == null) return;
2660 userData.clearSeedAccountData();
2661 }
2662 writeUserLP(userData);
2663 }
2664 }
2665
2666 @Override
2667 public boolean someUserHasSeedAccount(String accountName, String accountType)
2668 throws RemoteException {
2669 checkManageUsersPermission("Cannot check seed account information");
2670 synchronized (mUsersLock) {
2671 final int userSize = mUsers.size();
2672 for (int i = 0; i < userSize; i++) {
2673 final UserData data = mUsers.valueAt(i);
2674 if (data.info.isInitialized()) continue;
2675 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2676 continue;
2677 }
2678 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2679 continue;
2680 }
2681 return true;
2682 }
2683 }
2684 return false;
2685 }
2686
2687 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002688 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2689 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2690 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2691 }
2692
2693 int onShellCommand(Shell shell, String cmd) {
2694 if (cmd == null) {
2695 return shell.handleDefaultCommands(cmd);
2696 }
2697
2698 final PrintWriter pw = shell.getOutPrintWriter();
2699 try {
2700 switch(cmd) {
2701 case "list":
2702 return runList(pw);
2703 }
2704 } catch (RemoteException e) {
2705 pw.println("Remote exception: " + e);
2706 }
2707 return -1;
2708 }
2709
2710 private int runList(PrintWriter pw) throws RemoteException {
2711 final IActivityManager am = ActivityManagerNative.getDefault();
2712 final List<UserInfo> users = getUsers(false);
2713 if (users == null) {
2714 pw.println("Error: couldn't get users");
2715 return 1;
2716 } else {
2717 pw.println("Users:");
2718 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002719 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002720 pw.println("\t" + users.get(i).toString() + running);
2721 }
2722 return 0;
2723 }
2724 }
2725
2726 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002727 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2728 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2729 != PackageManager.PERMISSION_GRANTED) {
2730 pw.println("Permission Denial: can't dump UserManager from from pid="
2731 + Binder.getCallingPid()
2732 + ", uid=" + Binder.getCallingUid()
2733 + " without permission "
2734 + android.Manifest.permission.DUMP);
2735 return;
2736 }
2737
2738 long now = System.currentTimeMillis();
2739 StringBuilder sb = new StringBuilder();
2740 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002741 synchronized (mUsersLock) {
2742 pw.println("Users:");
2743 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002744 UserData userData = mUsers.valueAt(i);
2745 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002746 continue;
2747 }
Amith Yamasani12747872015-12-07 14:19:49 -08002748 UserInfo userInfo = userData.info;
2749 final int userId = userInfo.id;
2750 pw.print(" "); pw.print(userInfo);
2751 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002752 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002753 pw.print(" <removing> ");
2754 }
Amith Yamasani12747872015-12-07 14:19:49 -08002755 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002756 pw.print(" <partial>");
2757 }
2758 pw.println();
2759 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002760 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002761 pw.println("<unknown>");
2762 } else {
2763 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002764 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002765 sb.append(" ago");
2766 pw.println(sb);
2767 }
2768 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002769 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002770 pw.println("<unknown>");
2771 } else {
2772 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002773 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002774 sb.append(" ago");
2775 pw.println(sb);
2776 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002777 pw.print(" Has profile owner: ");
2778 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002779 pw.println(" Restrictions:");
2780 synchronized (mRestrictionsLock) {
2781 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002782 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002783 pw.println(" Device policy local restrictions:");
2784 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002785 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002786 pw.println(" Effective restrictions:");
2787 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002788 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002789 }
Amith Yamasani12747872015-12-07 14:19:49 -08002790
2791 if (userData.account != null) {
2792 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002793 pw.println();
2794 }
Amith Yamasani12747872015-12-07 14:19:49 -08002795
2796 if (userData.seedAccountName != null) {
2797 pw.print(" Seed account name: " + userData.seedAccountName);
2798 pw.println();
2799 if (userData.seedAccountType != null) {
2800 pw.print(" account type: " + userData.seedAccountType);
2801 pw.println();
2802 }
2803 if (userData.seedAccountOptions != null) {
2804 pw.print(" account options exist");
2805 pw.println();
2806 }
2807 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002808 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002809 }
Amith Yamasani12747872015-12-07 14:19:49 -08002810 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002811 pw.println(" Device policy global restrictions:");
2812 synchronized (mRestrictionsLock) {
2813 UserRestrictionsUtils
2814 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2815 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002816 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002817 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002818 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002819 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002820 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002821 synchronized (mUsersLock) {
2822 pw.println();
2823 pw.println(" Device managed: " + mIsDeviceManaged);
2824 }
Amith Yamasani12747872015-12-07 14:19:49 -08002825 // Dump some capabilities
2826 pw.println();
2827 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2828 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002829 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2830 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002831 }
2832 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002833
2834 final class MainHandler extends Handler {
2835
2836 @Override
2837 public void handleMessage(Message msg) {
2838 switch (msg.what) {
2839 case WRITE_USER_MSG:
2840 removeMessages(WRITE_USER_MSG, msg.obj);
2841 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002842 int userId = ((UserData) msg.obj).info.id;
2843 UserData userData = getUserDataNoChecks(userId);
2844 if (userData != null) {
2845 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002846 }
2847 }
2848 }
2849 }
2850 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002851
2852 /**
2853 * @param userId
2854 * @return whether the user has been initialized yet
2855 */
2856 boolean isInitialized(int userId) {
2857 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2858 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002859
2860 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002861 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002862 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2863 @Nullable Bundle globalRestrictions) {
2864 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2865 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002866 }
2867
2868 @Override
2869 public Bundle getBaseUserRestrictions(int userId) {
2870 synchronized (mRestrictionsLock) {
2871 return mBaseUserRestrictions.get(userId);
2872 }
2873 }
2874
2875 @Override
2876 public void setBaseUserRestrictionsByDpmsForMigration(
2877 int userId, Bundle baseRestrictions) {
2878 synchronized (mRestrictionsLock) {
2879 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002880 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002881 }
2882
Amith Yamasani12747872015-12-07 14:19:49 -08002883 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002884 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002885 if (userData != null) {
2886 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002887 } else {
2888 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2889 }
2890 }
2891 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002892
2893 @Override
2894 public boolean getUserRestriction(int userId, String key) {
2895 return getUserRestrictions(userId).getBoolean(key);
2896 }
2897
2898 @Override
2899 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2900 synchronized (mUserRestrictionsListeners) {
2901 mUserRestrictionsListeners.add(listener);
2902 }
2903 }
2904
2905 @Override
2906 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2907 synchronized (mUserRestrictionsListeners) {
2908 mUserRestrictionsListeners.remove(listener);
2909 }
2910 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002911
2912 @Override
2913 public void setDeviceManaged(boolean isManaged) {
2914 synchronized (mUsersLock) {
2915 mIsDeviceManaged = isManaged;
2916 }
2917 }
2918
2919 @Override
2920 public void setUserManaged(int userId, boolean isManaged) {
2921 synchronized (mUsersLock) {
2922 mIsUserManaged.put(userId, isManaged);
2923 }
2924 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01002925
2926 @Override
2927 public void setUserIcon(int userId, Bitmap bitmap) {
2928 long ident = Binder.clearCallingIdentity();
2929 try {
2930 synchronized (mPackagesLock) {
2931 UserData userData = getUserDataNoChecks(userId);
2932 if (userData == null || userData.info.partial) {
2933 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
2934 return;
2935 }
2936 writeBitmapLP(userData.info, bitmap);
2937 writeUserLP(userData);
2938 }
2939 sendUserInfoChangedBroadcast(userId);
2940 } finally {
2941 Binder.restoreCallingIdentity(ident);
2942 }
2943 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002944
2945 @Override
2946 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
2947 synchronized (mUsersLock) {
2948 mForceEphemeralUsers = forceEphemeralUsers;
2949 }
2950 }
2951
2952 @Override
2953 public void removeAllUsers() {
2954 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
2955 // Remove the non-system users straight away.
2956 removeNonSystemUsers();
2957 } else {
2958 // Switch to the system user first and then remove the other users.
2959 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
2960 @Override
2961 public void onReceive(Context context, Intent intent) {
2962 int userId =
2963 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2964 if (userId != UserHandle.USER_SYSTEM) {
2965 return;
2966 }
2967 mContext.unregisterReceiver(this);
2968 removeNonSystemUsers();
2969 }
2970 };
2971 IntentFilter userSwitchedFilter = new IntentFilter();
2972 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
2973 mContext.registerReceiver(
2974 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
2975
2976 // Switch to the system user.
2977 ActivityManager am =
2978 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
2979 am.switchUser(UserHandle.USER_SYSTEM);
2980 }
2981 }
phweisse9c44062016-02-10 12:57:38 +01002982
2983 @Override
2984 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
2985 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
2986 // Keep this in sync with UserManager.createUser
2987 if (user != null && !user.isAdmin()) {
2988 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
2989 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
2990 }
2991 return user;
2992 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002993 }
2994
2995 /* Remove all the users except of the system one. */
2996 private void removeNonSystemUsers() {
2997 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
2998 synchronized (mUsersLock) {
2999 final int userSize = mUsers.size();
3000 for (int i = 0; i < userSize; i++) {
3001 UserInfo ui = mUsers.valueAt(i).info;
3002 if (ui.id != UserHandle.USER_SYSTEM) {
3003 usersToRemove.add(ui);
3004 }
3005 }
3006 }
3007 for (UserInfo ui: usersToRemove) {
3008 removeUser(ui.id);
3009 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003010 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003011
3012 private class Shell extends ShellCommand {
3013 @Override
3014 public int onCommand(String cmd) {
3015 return onShellCommand(this, cmd);
3016 }
3017
3018 @Override
3019 public void onHelp() {
3020 final PrintWriter pw = getOutPrintWriter();
3021 pw.println("User manager (user) commands:");
3022 pw.println(" help");
3023 pw.println(" Print this help text.");
3024 pw.println("");
3025 pw.println(" list");
3026 pw.println(" Prints all users on the system.");
3027 }
3028 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003029
3030 private static void debug(String message) {
3031 Log.d(LOG_TAG, message +
3032 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3033 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003034}