blob: 5342f98d4abe827a2bf005330331a645ab7ca0cc [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chenb3b92582015-12-07 11:22:13 -080019import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070021import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070022import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070023import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070024import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070026import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010031import android.content.IntentFilter;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070032import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070033import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080034import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070035import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010036import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070037import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070038import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080039import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080040import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070041import android.os.Environment;
42import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080043import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080044import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080046import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010047import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070048import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080049import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070050import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070051import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070052import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010053import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040054import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070055import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070056import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070057import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070058import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080059import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010060import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070061import android.os.storage.VolumeInfo;
62import android.system.ErrnoException;
63import android.system.Os;
64import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070065import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070066import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import android.util.Slog;
68import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080069import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070070import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070071import android.util.Xml;
72
Makoto Onuki068c54a2015-10-13 14:34:03 -070073import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070074import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040075import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080076import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080077import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070078import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070079import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000080import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070081import com.android.server.LocalServices;
Jeff Sharkey47f71082016-02-01 17:03:54 -070082
83import libcore.io.IoUtils;
84import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080085
86import org.xmlpull.v1.XmlPullParser;
87import org.xmlpull.v1.XmlPullParserException;
88import org.xmlpull.v1.XmlSerializer;
89
Amith Yamasani4b2e9342011-03-31 12:38:53 -070090import java.io.BufferedOutputStream;
91import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070092import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070094import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095import java.io.FileOutputStream;
96import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070097import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010098import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099import java.util.ArrayList;
100import java.util.List;
101
Makoto Onuki068c54a2015-10-13 14:34:03 -0700102/**
103 * Service for {@link UserManager}.
104 *
105 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700106 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800107 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700108 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
109 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
110 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700111 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700112public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700113 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800114 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800115 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700116
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800118 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700120 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700122 private static final String ATTR_CREATION_TIME = "created";
123 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700124 private static final String ATTR_SERIAL_NO = "serialNumber";
125 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700126 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700127 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700128 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100129 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700130 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800131 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
132 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530133 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700135 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800136 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800137 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800138 private static final String TAG_ENTRY = "entry";
139 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800140 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800141 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700142 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800143 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700145 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
146 private static final String ATTR_TYPE_STRING = "s";
147 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700148 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700149 private static final String ATTR_TYPE_BUNDLE = "B";
150 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700151
Amith Yamasani0b285492011-04-14 17:35:23 -0700152 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700153 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700154 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100155 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700156
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800157 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700158 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800159
Amith Yamasani634cf312012-10-04 17:34:21 -0700160 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700161 // We need to keep process uid within Integer.MAX_VALUE.
162 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700163
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700164 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700165
Amith Yamasani920ace02012-09-20 22:15:37 -0700166 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
167
Nicolas Prevotb8186812015-08-06 15:00:03 +0100168 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700169 // without first making sure that the rest of the framework is prepared for it.
170 private static final int MAX_MANAGED_PROFILES = 1;
171
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800172 static final int WRITE_USER_MSG = 1;
173 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530174
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700175 private static final String XATTR_SERIAL = "user.serial";
176
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800177 // Tron counters
178 private static final String TRON_GUEST_CREATED = "users_guest_created";
179 private static final String TRON_USER_CREATED = "users_user_created";
180
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 private final Context mContext;
182 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700183 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700184 // Short-term lock for internal state, when interaction/sync with PM is not required
185 private final Object mUsersLock = new Object();
186 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700187
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800188 private final Handler mHandler;
189
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190 private final File mUsersDir;
191 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700192
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800193 private static final IBinder mUserRestriconToken = new Binder();
194
Makoto Onuki068c54a2015-10-13 14:34:03 -0700195 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800196 * User-related information that is used for persisting to flash. Only UserInfo is
197 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800198 */
Amith Yamasani12747872015-12-07 14:19:49 -0800199 private static class UserData {
200 // Basic user information and properties
201 UserInfo info;
202 // Account name used when there is a strong association between a user and an account
203 String account;
204 // Account information for seeding into a newly created user. This could also be
205 // used for login validation for an existing user, for updating their credentials.
206 // In the latter case, data may not need to be persisted as it is only valid for the
207 // current login session.
208 String seedAccountName;
209 String seedAccountType;
210 PersistableBundle seedAccountOptions;
211 // Whether to perist the seed account information to be available after a boot
212 boolean persistSeedData;
213
214 void clearSeedAccountData() {
215 seedAccountName = null;
216 seedAccountType = null;
217 seedAccountOptions = null;
218 persistSeedData = false;
219 }
220 }
221
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800222 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800223 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800224
225 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700226 * User restrictions set via UserManager. This doesn't include restrictions set by
227 * device owner / profile owners.
228 *
229 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
230 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
231 * maybe shared between {@link #mBaseUserRestrictions} and
232 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
233 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700234 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700235 */
236 @GuardedBy("mRestrictionsLock")
237 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
238
239 /**
240 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
241 * with device / profile owner restrictions. We'll initialize it lazily; use
242 * {@link #getEffectiveUserRestrictions} to access it.
243 *
244 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
245 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
246 * maybe shared between {@link #mBaseUserRestrictions} and
247 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
248 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700249 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700250 */
251 @GuardedBy("mRestrictionsLock")
252 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
253
Makoto Onuki4f160732015-10-27 17:15:38 -0700254 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800255 * User restrictions that have already been applied in
256 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
257 * that have changed since the last
258 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700259 */
260 @GuardedBy("mRestrictionsLock")
261 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
262
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800263 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800264 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
265 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800266 */
267 @GuardedBy("mRestrictionsLock")
268 private Bundle mDevicePolicyGlobalUserRestrictions;
269
270 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800271 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
272 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800273 */
274 @GuardedBy("mRestrictionsLock")
275 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
276
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800277 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530278 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800279
280 /**
281 * Set of user IDs being actively removed. Removed IDs linger in this set
282 * for several seconds to work around a VFS caching issue.
283 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700284 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800285 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700286
Fyodor Kupolov82402752015-10-28 14:54:51 -0700287 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700288 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800289 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700290 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700291 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700292
Jason Monk62062992014-05-06 09:55:28 -0400293 private IAppOpsService mAppOpsService;
294
Makoto Onuki068c54a2015-10-13 14:34:03 -0700295 private final LocalService mLocalService;
296
Makoto Onukie7927da2015-11-25 10:05:17 -0800297 @GuardedBy("mUsersLock")
298 private boolean mIsDeviceManaged;
299
300 @GuardedBy("mUsersLock")
301 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
302
Makoto Onukid45a4a22015-11-02 17:17:38 -0800303 @GuardedBy("mUserRestrictionsListeners")
304 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
305 new ArrayList<>();
306
Clara Bayarria1771112015-12-18 16:29:18 +0000307 private final LockPatternUtils mLockPatternUtils;
308
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100309 /**
310 * Whether all users should be created ephemeral.
311 */
312 @GuardedBy("mUsersLock")
313 private boolean mForceEphemeralUsers;
314
Amith Yamasani258848d2012-08-10 17:06:33 -0700315 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700316
Dianne Hackborn4428e172012-08-24 17:43:05 -0700317 public static UserManagerService getInstance() {
318 synchronized (UserManagerService.class) {
319 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700320 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700321 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700322
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800323 @VisibleForTesting
324 UserManagerService(File dataDir) {
325 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700326 }
327
Dianne Hackborn4428e172012-08-24 17:43:05 -0700328 /**
329 * Called by package manager to create the service. This is closely
330 * associated with the package manager, and the given lock is the
331 * package manager's own lock.
332 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800333 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
334 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700335 }
336
Dianne Hackborn4428e172012-08-24 17:43:05 -0700337 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800338 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700339 mContext = context;
340 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700341 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800342 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800343 synchronized (mPackagesLock) {
344 mUsersDir = new File(dataDir, USER_INFO_DIR);
345 mUsersDir.mkdirs();
346 // Make zeroth user directory, for services to migrate their files to that location
347 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
348 userZeroDir.mkdirs();
349 FileUtils.setPermissions(mUsersDir.toString(),
350 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
351 -1, -1);
352 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
353 initDefaultGuestRestrictions();
354 readUserListLP();
355 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700356 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700357 mLocalService = new LocalService();
358 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000359 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700360 }
361
362 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100363 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800364 ArrayList<UserInfo> partials = new ArrayList<>();
365 synchronized (mUsersLock) {
366 final int userSize = mUsers.size();
367 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800368 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100369 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800370 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700371 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700372 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700373 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800374 final int partialsSize = partials.size();
375 for (int i = 0; i < partialsSize; i++) {
376 UserInfo ui = partials.get(i);
377 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
378 + " (name=" + ui.name + ")");
379 removeUserState(ui.id);
380 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800381
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700382 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800383
Jason Monk62062992014-05-06 09:55:28 -0400384 mAppOpsService = IAppOpsService.Stub.asInterface(
385 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800386
387 synchronized (mRestrictionsLock) {
388 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400389 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700390 }
391
392 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800393 public String getUserAccount(int userId) {
394 checkManageUserAndAcrossUsersFullPermission("get user account");
395 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800396 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800397 }
398 }
399
400 @Override
401 public void setUserAccount(int userId, String accountName) {
402 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800403 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800404 synchronized (mPackagesLock) {
405 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800406 final UserData userData = mUsers.get(userId);
407 if (userData == null) {
408 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
409 return;
410 }
411 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800412 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800413 userData.account = accountName;
414 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800415 }
416 }
417
418 if (userToUpdate != null) {
419 writeUserLP(userToUpdate);
420 }
421 }
422 }
423
424 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700425 public UserInfo getPrimaryUser() {
426 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700427 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700428 final int userSize = mUsers.size();
429 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800430 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800431 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700432 return ui;
433 }
434 }
435 }
436 return null;
437 }
438
439 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700440 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700441 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700442 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700443 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700444 final int userSize = mUsers.size();
445 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800446 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700447 if (ui.partial) {
448 continue;
449 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800450 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700451 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700452 }
Amith Yamasani13593602012-03-22 16:16:17 -0700453 }
454 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700455 }
Amith Yamasani13593602012-03-22 16:16:17 -0700456 }
457
Amith Yamasani258848d2012-08-10 17:06:33 -0700458 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100459 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800460 if (userId != UserHandle.getCallingUserId()) {
461 checkManageUsersPermission("getting profiles related to user " + userId);
462 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700463 final long ident = Binder.clearCallingIdentity();
464 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700465 synchronized (mUsersLock) {
466 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100467 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700468 } finally {
469 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000470 }
471 }
472
Amith Yamasanibe465322014-04-24 13:45:17 -0700473 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700474 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
475 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700476 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700477 if (user == null) {
478 // Probably a dying user
479 return users;
480 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700481 final int userSize = mUsers.size();
482 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800483 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700484 if (!isProfileOf(user, profile)) {
485 continue;
486 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100487 if (enabledOnly && !profile.isEnabled()) {
488 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700489 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700490 if (mRemovingUserIds.get(profile.id)) {
491 continue;
492 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700493 users.add(profile);
494 }
495 return users;
496 }
497
Jessica Hummelbe81c802014-04-22 15:49:22 +0100498 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700499 public int getCredentialOwnerProfile(int userHandle) {
500 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000501 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700502 synchronized (mUsersLock) {
503 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700504 if (profileParent != null) {
505 return profileParent.id;
506 }
507 }
508 }
509
510 return userHandle;
511 }
512
513 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700514 public boolean isSameProfileGroup(int userId, int otherUserId) {
515 if (userId == otherUserId) return true;
516 checkManageUsersPermission("check if in the same profile group");
517 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700518 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700519 }
520 }
521
Fyodor Kupolov82402752015-10-28 14:54:51 -0700522 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
523 synchronized (mUsersLock) {
524 UserInfo userInfo = getUserInfoLU(userId);
525 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
526 return false;
527 }
528 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
529 if (otherUserInfo == null
530 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
531 return false;
532 }
533 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700534 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700535 }
536
537 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100538 public UserInfo getProfileParent(int userHandle) {
539 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700540 synchronized (mUsersLock) {
541 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700542 }
543 }
544
Fyodor Kupolov82402752015-10-28 14:54:51 -0700545 private UserInfo getProfileParentLU(int userHandle) {
546 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700547 if (profile == null) {
548 return null;
549 }
550 int parentUserId = profile.profileGroupId;
551 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
552 return null;
553 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700554 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100555 }
556 }
557
Fyodor Kupolov82402752015-10-28 14:54:51 -0700558 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100559 return user.id == profile.id ||
560 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
561 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000562 }
563
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000564 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000565 UserHandle parentHandle, boolean inQuietMode) {
566 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
567 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
568 intent.putExtra(Intent.EXTRA_USER, profileHandle);
569 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000570 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000571 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000572 }
573
574 @Override
575 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
576 checkManageUsersPermission("silence profile");
577 boolean changed = false;
578 UserInfo profile, parent;
579 synchronized (mPackagesLock) {
580 synchronized (mUsersLock) {
581 profile = getUserInfoLU(userHandle);
582 parent = getProfileParentLU(userHandle);
583
584 }
585 if (profile == null || !profile.isManagedProfile()) {
586 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
587 }
588 if (profile.isQuietModeEnabled() != enableQuietMode) {
589 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800590 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000591 changed = true;
592 }
593 }
594 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000595 long identity = Binder.clearCallingIdentity();
596 try {
597 if (enableQuietMode) {
598 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
599 } else {
600 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
601 }
602 } catch (RemoteException e) {
603 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
604 } finally {
605 Binder.restoreCallingIdentity(identity);
606 }
607
608 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
609 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000610 }
611 }
612
613 @Override
614 public boolean isQuietModeEnabled(int userHandle) {
615 synchronized (mPackagesLock) {
616 UserInfo info;
617 synchronized (mUsersLock) {
618 info = getUserInfoLU(userHandle);
619 }
620 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000621 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000622 }
623 return info.isQuietModeEnabled();
624 }
625 }
626
Kenny Guya52dc3e2014-02-11 15:33:14 +0000627 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100628 public void setUserEnabled(int userId) {
629 checkManageUsersPermission("enable user");
630 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700631 UserInfo info;
632 synchronized (mUsersLock) {
633 info = getUserInfoLU(userId);
634 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100635 if (info != null && !info.isEnabled()) {
636 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800637 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100638 }
639 }
640 }
641
642 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700643 public UserInfo getUserInfo(int userId) {
Tony Mak4dc008c2016-03-16 10:46:49 +0000644 if (!hasManageUsersPermission()
645 && !isSameProfileGroupLP(UserHandle.getCallingUserId(), userId)) {
646 throw new SecurityException(
647 "You need MANAGE_USERS permission to: query users outside profile group");
648 }
649
Fyodor Kupolov82402752015-10-28 14:54:51 -0700650 synchronized (mUsersLock) {
651 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700652 }
653 }
654
Amith Yamasani71e6c692013-03-24 17:39:28 -0700655 @Override
656 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700657 synchronized (mUsersLock) {
658 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700659 }
660 }
661
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700662 @Override
663 public boolean canHaveRestrictedProfile(int userId) {
664 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700665 synchronized (mUsersLock) {
666 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700667 if (userInfo == null || !userInfo.canHaveProfile()) {
668 return false;
669 }
670 if (!userInfo.isAdmin()) {
671 return false;
672 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800673 // restricted profile can be created if there is no DO set and the admin user has no PO;
674 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700675 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700676 }
677
Amith Yamasani195263742012-08-21 15:40:12 -0700678 /*
679 * Should be locked on mUsers before calling this.
680 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700681 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800682 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700683 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800684 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700685 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
686 return null;
687 }
Amith Yamasani12747872015-12-07 14:19:49 -0800688 return userData != null ? userData.info : null;
689 }
690
691 private UserData getUserDataLU(int userId) {
692 final UserData userData = mUsers.get(userId);
693 // If it is partial and not in the process of being removed, return as unknown user.
694 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
695 return null;
696 }
697 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700698 }
699
Fyodor Kupolov82402752015-10-28 14:54:51 -0700700 /**
701 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
702 * <p>No permissions checking or any addition checks are made</p>
703 */
704 private UserInfo getUserInfoNoChecks(int userId) {
705 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800706 final UserData userData = mUsers.get(userId);
707 return userData != null ? userData.info : null;
708 }
709 }
710
711 /**
712 * Obtains {@link #mUsersLock} and return UserData from mUsers.
713 * <p>No permissions checking or any addition checks are made</p>
714 */
715 private UserData getUserDataNoChecks(int userId) {
716 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700717 return mUsers.get(userId);
718 }
719 }
720
Amith Yamasani236b2b52015-08-18 14:32:14 -0700721 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700722 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700723 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700724 }
725
Amith Yamasani258848d2012-08-10 17:06:33 -0700726 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700727 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700728 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700729 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700730 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800731 UserData userData = getUserDataNoChecks(userId);
732 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700733 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
734 return;
735 }
Amith Yamasani12747872015-12-07 14:19:49 -0800736 if (name != null && !name.equals(userData.info.name)) {
737 userData.info.name = name;
738 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700739 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700740 }
741 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700742 if (changed) {
743 sendUserInfoChangedBroadcast(userId);
744 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700745 }
746
Amith Yamasani258848d2012-08-10 17:06:33 -0700747 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700748 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700749 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100750 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
751 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
752 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700753 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100754 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700755 }
756
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100757
758
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700759 private void sendUserInfoChangedBroadcast(int userId) {
760 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
761 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
762 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700763 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700764 }
765
Amith Yamasani258848d2012-08-10 17:06:33 -0700766 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100767 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100768 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700769 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100770 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
771 if (targetUserInfo == null || targetUserInfo.partial) {
772 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700773 return null;
774 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100775
776 final int callingUserId = UserHandle.getCallingUserId();
777 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
778 final int targetGroupId = targetUserInfo.profileGroupId;
779 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
780 && callingGroupId == targetGroupId);
781 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100782 checkManageUsersPermission("get the icon of a user who is not related");
783 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100784
785 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700786 return null;
787 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100788 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700789 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100790
791 try {
792 return ParcelFileDescriptor.open(
793 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
794 } catch (FileNotFoundException e) {
795 Log.e(LOG_TAG, "Couldn't find icon file", e);
796 }
797 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700798 }
799
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700800 public void makeInitialized(int userId) {
801 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800802 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800803 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800804 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800805 userData = mUsers.get(userId);
806 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700807 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800808 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700809 }
Amith Yamasani12747872015-12-07 14:19:49 -0800810 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
811 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800812 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700813 }
814 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800815 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800816 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800817 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700818 }
819
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700820 /**
821 * If default guest restrictions haven't been initialized yet, add the basic
822 * restrictions.
823 */
824 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800825 synchronized (mGuestRestrictions) {
826 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800827 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800828 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
829 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
830 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700831 }
832 }
833
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800834 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530835 public Bundle getDefaultGuestRestrictions() {
836 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800837 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530838 return new Bundle(mGuestRestrictions);
839 }
840 }
841
842 @Override
843 public void setDefaultGuestRestrictions(Bundle restrictions) {
844 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800845 synchronized (mGuestRestrictions) {
846 mGuestRestrictions.clear();
847 mGuestRestrictions.putAll(restrictions);
848 }
849 synchronized (mPackagesLock) {
850 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530851 }
852 }
853
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800854 /**
855 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
856 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800857 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800858 @Nullable Bundle global) {
859 Preconditions.checkNotNull(local);
860 boolean globalChanged = false;
861 boolean localChanged;
862 synchronized (mRestrictionsLock) {
863 if (global != null) {
864 // Update global.
865 globalChanged = !UserRestrictionsUtils.areEqual(
866 mDevicePolicyGlobalUserRestrictions, global);
867 if (globalChanged) {
868 mDevicePolicyGlobalUserRestrictions = global;
869 }
870 }
871 {
872 // Update local.
873 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
874 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
875 if (localChanged) {
876 mDevicePolicyLocalUserRestrictions.put(userId, local);
877 }
878 }
879 }
880 if (DBG) {
881 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
882 + " global=" + global + (globalChanged ? " (changed)" : "")
883 + " local=" + local + (localChanged ? " (changed)" : "")
884 );
885 }
886 // Don't call them within the mRestrictionsLock.
887 synchronized (mPackagesLock) {
888 if (globalChanged) {
889 writeUserListLP();
890 }
891 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800892 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800893 }
894 }
895
896 synchronized (mRestrictionsLock) {
897 if (globalChanged) {
898 applyUserRestrictionsForAllUsersLR();
899 } else if (localChanged) {
900 applyUserRestrictionsLR(userId);
901 }
902 }
903 }
904
Makoto Onuki068c54a2015-10-13 14:34:03 -0700905 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700906 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800907 final Bundle baseRestrictions =
908 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
909 final Bundle global = mDevicePolicyGlobalUserRestrictions;
910 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700911
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800912 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
913 // Common case first.
914 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700915 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800916 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
917 UserRestrictionsUtils.merge(effective, global);
918 UserRestrictionsUtils.merge(effective, local);
919
Makoto Onuki068c54a2015-10-13 14:34:03 -0700920 return effective;
921 }
922
923 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700924 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700925 if (DBG) {
926 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
927 }
928 mCachedEffectiveUserRestrictions.remove(userId);
929 }
930
931 private Bundle getEffectiveUserRestrictions(int userId) {
932 synchronized (mRestrictionsLock) {
933 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
934 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700935 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700936 mCachedEffectiveUserRestrictions.put(userId, restrictions);
937 }
938 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700939 }
940 }
941
Makoto Onuki068c54a2015-10-13 14:34:03 -0700942 /** @return a specific user restriction that's in effect currently. */
943 @Override
944 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800945 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
946 return false;
947 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700948 Bundle restrictions = getEffectiveUserRestrictions(userId);
949 return restrictions != null && restrictions.getBoolean(restrictionKey);
950 }
951
952 /**
953 * @return UserRestrictions that are in effect currently. This always returns a new
954 * {@link Bundle}.
955 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700956 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800957 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800958 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800959 }
960
961 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000962 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
963 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800964 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
965 return false;
966 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000967 synchronized (mRestrictionsLock) {
968 Bundle bundle = mBaseUserRestrictions.get(userId);
969 return (bundle != null && bundle.getBoolean(restrictionKey, false));
970 }
971 }
972
973 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700974 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700975 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800976 if (!UserRestrictionsUtils.isValidRestriction(key)) {
977 return;
978 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700979 synchronized (mRestrictionsLock) {
980 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
981 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800982 final Bundle newRestrictions = UserRestrictionsUtils.clone(
983 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700984 newRestrictions.putBoolean(key, value);
985
Fyodor Kupolov82402752015-10-28 14:54:51 -0700986 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700987 }
988 }
989
Makoto Onuki068c54a2015-10-13 14:34:03 -0700990 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800991 * Optionally updating user restrictions, calculate the effective user restrictions and also
992 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700993 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800994 * @param newRestrictions User restrictions to set.
995 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700996 * @param userId target user ID.
997 */
998 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700999 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001000 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001001
1002 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1003 mAppliedUserRestrictions.get(userId));
1004
1005 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001006 if (newRestrictions != null) {
1007 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001008 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1009
1010 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001011 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1012 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001013
1014 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1015 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001016 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001017 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001018 }
1019
Fyodor Kupolov82402752015-10-28 14:54:51 -07001020 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001021
Makoto Onuki759a7632015-10-28 16:43:10 -07001022 mCachedEffectiveUserRestrictions.put(userId, effective);
1023
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001024 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001025 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001026 debug("Applying user restrictions: userId=" + userId
1027 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001028 }
1029
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001030 if (mAppOpsService != null) { // We skip it until system-ready.
1031 final long token = Binder.clearCallingIdentity();
1032 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001033 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001034 } catch (RemoteException e) {
1035 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1036 } finally {
1037 Binder.restoreCallingIdentity(token);
1038 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001039 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001040
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001041 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001042
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001043 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001044 }
1045
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001046 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001047 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001048 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1049 // actually, but we still need some kind of synchronization otherwise we might end up
1050 // calling listeners out-of-order, thus "LR".
1051
1052 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1053 return;
1054 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001055
1056 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1057 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1058
1059 mHandler.post(new Runnable() {
1060 @Override
1061 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001062 UserRestrictionsUtils.applyUserRestrictions(
1063 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001064
Makoto Onukid45a4a22015-11-02 17:17:38 -08001065 final UserRestrictionsListener[] listeners;
1066 synchronized (mUserRestrictionsListeners) {
1067 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1068 mUserRestrictionsListeners.toArray(listeners);
1069 }
1070 for (int i = 0; i < listeners.length; i++) {
1071 listeners[i].onUserRestrictionsChanged(userId,
1072 newRestrictionsFinal, prevRestrictionsFinal);
1073 }
1074 }
1075 });
1076 }
1077
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001078 // Package private for the inner class.
1079 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001080 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001081 }
1082
1083 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001084 // Package private for the inner class.
1085 void applyUserRestrictionsForAllUsersLR() {
1086 if (DBG) {
1087 debug("applyUserRestrictionsForAllUsersLR");
1088 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001089 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001090 mCachedEffectiveUserRestrictions.clear();
1091
Makoto Onuki068c54a2015-10-13 14:34:03 -07001092 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1093 // it on a handler.
1094 final Runnable r = new Runnable() {
1095 @Override
1096 public void run() {
1097 // Then get the list of running users.
1098 final int[] runningUsers;
1099 try {
1100 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1101 } catch (RemoteException e) {
1102 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1103 return;
1104 }
1105 // Then re-calculate the effective restrictions and apply, only for running users.
1106 // It's okay if a new user has started after the getRunningUserIds() call,
1107 // because we'll do the same thing (re-calculate the restrictions and apply)
1108 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001109 synchronized (mRestrictionsLock) {
1110 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001111 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001112 }
1113 }
1114 }
1115 };
1116 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001117 }
1118
Amith Yamasani258848d2012-08-10 17:06:33 -07001119 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001120 * Check if we've hit the limit of how many users can be created.
1121 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001122 private boolean isUserLimitReached() {
1123 int count;
1124 synchronized (mUsersLock) {
1125 count = getAliveUsersExcludingGuestsCountLU();
1126 }
1127 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001128 }
1129
1130 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001131 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001132 checkManageUsersPermission("check if more managed profiles can be added.");
1133 if (ActivityManager.isLowRamDeviceStatic()) {
1134 return false;
1135 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001136 if (!mContext.getPackageManager().hasSystemFeature(
1137 PackageManager.FEATURE_MANAGED_USERS)) {
1138 return false;
1139 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001140 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001141 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1142 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1143 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001144 return false;
1145 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001146 synchronized(mUsersLock) {
1147 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001148 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001149 return false;
1150 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001151 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1152 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001153 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001154 return usersCountAfterRemoving == 1
1155 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001156 }
1157 }
1158
Fyodor Kupolov82402752015-10-28 14:54:51 -07001159 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001160 int aliveUserCount = 0;
1161 final int totalUserCount = mUsers.size();
1162 // Skip over users being removed
1163 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001164 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001165 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001166 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001167 aliveUserCount++;
1168 }
1169 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001170 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001171 }
1172
1173 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001174 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001175 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1176 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1177 * permissions can make certain calls to the UserManager.
1178 *
1179 * @param message used as message if SecurityException is thrown
1180 * @throws SecurityException if the caller does not have enough privilege.
1181 */
1182 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1183 final int uid = Binder.getCallingUid();
1184 if (uid != Process.SYSTEM_UID && uid != 0
1185 && ActivityManager.checkComponentPermission(
1186 Manifest.permission.MANAGE_USERS,
1187 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1188 && ActivityManager.checkComponentPermission(
1189 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1190 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1191 throw new SecurityException(
1192 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1193 + message);
1194 }
1195 }
1196
1197 /**
1198 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001199 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001200 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001201 *
1202 * @param message used as message if SecurityException is thrown
1203 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001204 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001205 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001206 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001207 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001208 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1209 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001210 }
1211
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001212 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001213 * @return whether the calling UID is system UID or root's UID or the calling app has the
1214 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1215 */
1216 private static final boolean hasManageUsersPermission() {
1217 final int callingUid = Binder.getCallingUid();
1218 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1219 || callingUid == Process.ROOT_UID
1220 || ActivityManager.checkComponentPermission(
1221 android.Manifest.permission.MANAGE_USERS,
1222 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1223 }
1224
1225 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001226 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1227 * UserManager.
1228 *
1229 * @param message used as message if SecurityException is thrown
1230 * @throws SecurityException if the caller is not system or root
1231 */
1232 private static void checkSystemOrRoot(String message) {
1233 final int uid = Binder.getCallingUid();
1234 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1235 throw new SecurityException("Only system may: " + message);
1236 }
1237 }
1238
Fyodor Kupolov82402752015-10-28 14:54:51 -07001239 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001240 try {
1241 File dir = new File(mUsersDir, Integer.toString(info.id));
1242 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001243 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001244 if (!dir.exists()) {
1245 dir.mkdir();
1246 FileUtils.setPermissions(
1247 dir.getPath(),
1248 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1249 -1, -1);
1250 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001251 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001252 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001253 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001254 info.iconPath = file.getAbsolutePath();
1255 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001256 try {
1257 os.close();
1258 } catch (IOException ioe) {
1259 // What the ... !
1260 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001261 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001262 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001263 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001264 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001265 }
1266
Amith Yamasani0b285492011-04-14 17:35:23 -07001267 /**
1268 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1269 * cache it elsewhere.
1270 * @return the array of user ids.
1271 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001272 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001273 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001274 return mUserIds;
1275 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001276 }
1277
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001278 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001279 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001280 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001281 return;
1282 }
1283 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001284 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001285 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001286 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001287 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001288 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001289 int type;
1290 while ((type = parser.next()) != XmlPullParser.START_TAG
1291 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001292 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001293 }
1294
1295 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001296 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001297 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001298 return;
1299 }
1300
Amith Yamasani2a003292012-08-14 18:25:45 -07001301 mNextSerialNumber = -1;
1302 if (parser.getName().equals(TAG_USERS)) {
1303 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1304 if (lastSerialNumber != null) {
1305 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1306 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001307 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1308 if (versionNumber != null) {
1309 mUserVersion = Integer.parseInt(versionNumber);
1310 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001311 }
1312
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001313 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1314
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001315 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301316 if (type == XmlPullParser.START_TAG) {
1317 final String name = parser.getName();
1318 if (name.equals(TAG_USER)) {
1319 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001320
Amith Yamasani12747872015-12-07 14:19:49 -08001321 UserData userData = readUserLP(Integer.parseInt(id));
1322
1323 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001324 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001325 mUsers.put(userData.info.id, userData);
1326 if (mNextSerialNumber < 0
1327 || mNextSerialNumber <= userData.info.id) {
1328 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001329 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301330 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001331 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301332 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001333 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1334 && type != XmlPullParser.END_TAG) {
1335 if (type == XmlPullParser.START_TAG) {
1336 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001337 synchronized (mGuestRestrictions) {
1338 UserRestrictionsUtils
1339 .readRestrictions(parser, mGuestRestrictions);
1340 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001341 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1342 ) {
1343 UserRestrictionsUtils.readRestrictions(parser,
1344 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001345 }
1346 break;
1347 }
1348 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001349 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001350 }
1351 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001352 synchronized (mRestrictionsLock) {
1353 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1354 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001355 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001356 upgradeIfNecessaryLP();
1357 } catch (IOException | XmlPullParserException e) {
1358 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001359 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001360 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001361 }
1362 }
1363
Amith Yamasani6f34b412012-10-22 18:19:27 -07001364 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001365 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001366 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001367 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001368 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001369 int userVersion = mUserVersion;
1370 if (userVersion < 1) {
1371 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001372 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1373 if ("Primary".equals(userData.info.name)) {
1374 userData.info.name =
1375 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1376 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001377 }
1378 userVersion = 1;
1379 }
1380
Amith Yamasanibc9625052012-11-15 14:39:18 -08001381 if (userVersion < 2) {
1382 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001383 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1384 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1385 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1386 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001387 }
1388 userVersion = 2;
1389 }
1390
Amith Yamasani350962c2013-08-06 11:18:53 -07001391
Amith Yamasani5e486f52013-08-07 11:06:44 -07001392 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001393 userVersion = 4;
1394 }
1395
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001396 if (userVersion < 5) {
1397 initDefaultGuestRestrictions();
1398 userVersion = 5;
1399 }
1400
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001401 if (userVersion < 6) {
1402 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001403 synchronized (mUsersLock) {
1404 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001405 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001406 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001407 if (!splitSystemUser && userData.info.isRestricted()
1408 && (userData.info.restrictedProfileParentId
1409 == UserInfo.NO_PROFILE_GROUP_ID)) {
1410 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1411 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001412 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001413 }
1414 }
1415 userVersion = 6;
1416 }
1417
Amith Yamasani6f34b412012-10-22 18:19:27 -07001418 if (userVersion < USER_VERSION) {
1419 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1420 + USER_VERSION);
1421 } else {
1422 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001423
1424 if (originalVersion < mUserVersion) {
1425 writeUserListLP();
1426 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001427 }
1428 }
1429
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001430 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001431 int flags = UserInfo.FLAG_INITIALIZED;
1432 // In split system user mode, the admin and primary flags are assigned to the first human
1433 // user.
1434 if (!UserManager.isSplitSystemUser()) {
1435 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1436 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001437 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001438 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001439 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001440 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001441 UserData userData = new UserData();
1442 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001443 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001444 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001445 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001446 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001447 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001448
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001449 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001450 synchronized (mRestrictionsLock) {
1451 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1452 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001453
Fyodor Kupolov82402752015-10-28 14:54:51 -07001454 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001455 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001456
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001457 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001458 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001459 }
1460
Amith Yamasani12747872015-12-07 14:19:49 -08001461 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001462 if (DBG) {
1463 debug("scheduleWriteUser");
1464 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001465 // No need to wrap it within a lock -- worst case, we'll just post the same message
1466 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001467 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1468 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001469 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1470 }
1471 }
1472
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001473 /*
1474 * Writes the user file in this format:
1475 *
1476 * <user flags="20039023" id="0">
1477 * <name>Primary</name>
1478 * </user>
1479 */
Amith Yamasani12747872015-12-07 14:19:49 -08001480 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001481 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001482 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001483 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001484 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001485 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001486 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001487 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001488 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1489
1490 // XmlSerializer serializer = XmlUtils.serializerInstance();
1491 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001492 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001493 serializer.startDocument(null, true);
1494 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1495
Amith Yamasani12747872015-12-07 14:19:49 -08001496 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001497 serializer.startTag(null, TAG_USER);
1498 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001499 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001500 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001501 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1502 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1503 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001504 if (userInfo.iconPath != null) {
1505 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1506 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001507 if (userInfo.partial) {
1508 serializer.attribute(null, ATTR_PARTIAL, "true");
1509 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001510 if (userInfo.guestToRemove) {
1511 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1512 }
Kenny Guy2a764942014-04-02 13:29:20 +01001513 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1514 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1515 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001516 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001517 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1518 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1519 Integer.toString(userInfo.restrictedProfileParentId));
1520 }
Amith Yamasani12747872015-12-07 14:19:49 -08001521 // Write seed data
1522 if (userData.persistSeedData) {
1523 if (userData.seedAccountName != null) {
1524 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1525 }
1526 if (userData.seedAccountType != null) {
1527 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1528 }
1529 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001530 serializer.startTag(null, TAG_NAME);
1531 serializer.text(userInfo.name);
1532 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001533 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001534 UserRestrictionsUtils.writeRestrictions(serializer,
1535 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1536 UserRestrictionsUtils.writeRestrictions(serializer,
1537 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1538 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001539 }
Amith Yamasani12747872015-12-07 14:19:49 -08001540
1541 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001542 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001543 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001544 serializer.endTag(null, TAG_ACCOUNT);
1545 }
1546
Amith Yamasani12747872015-12-07 14:19:49 -08001547 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1548 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1549 userData.seedAccountOptions.saveToXml(serializer);
1550 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1551 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001552 serializer.endTag(null, TAG_USER);
1553
1554 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001555 userFile.finishWrite(fos);
1556 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001557 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001558 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001559 }
1560 }
1561
1562 /*
1563 * Writes the user list file in this format:
1564 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001565 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001566 * <user id="0"></user>
1567 * <user id="2"></user>
1568 * </users>
1569 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001570 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001571 if (DBG) {
1572 debug("writeUserList");
1573 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001574 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001575 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001576 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001577 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001578 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1579
1580 // XmlSerializer serializer = XmlUtils.serializerInstance();
1581 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001582 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001583 serializer.startDocument(null, true);
1584 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1585
1586 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001587 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001588 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001589
Adam Lesinskieddeb492014-09-08 17:50:03 -07001590 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001591 synchronized (mGuestRestrictions) {
1592 UserRestrictionsUtils
1593 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1594 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301595 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001596 synchronized (mRestrictionsLock) {
1597 UserRestrictionsUtils.writeRestrictions(serializer,
1598 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1599 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001600 int[] userIdsToWrite;
1601 synchronized (mUsersLock) {
1602 userIdsToWrite = new int[mUsers.size()];
1603 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001604 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001605 userIdsToWrite[i] = user.id;
1606 }
1607 }
1608 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001609 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001610 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001611 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001612 }
1613
1614 serializer.endTag(null, TAG_USERS);
1615
1616 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001617 userListFile.finishWrite(fos);
1618 } catch (Exception e) {
1619 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001620 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001621 }
1622 }
1623
Amith Yamasani12747872015-12-07 14:19:49 -08001624 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001625 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001626 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001627 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001628 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001629 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001630 long creationTime = 0L;
1631 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001632 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001633 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001634 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001635 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001636 boolean persistSeedData = false;
1637 String seedAccountName = null;
1638 String seedAccountType = null;
1639 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001640 Bundle baseRestrictions = new Bundle();
1641 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001642
1643 FileInputStream fis = null;
1644 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001645 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001646 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001647 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001648 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001649 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001650 int type;
1651 while ((type = parser.next()) != XmlPullParser.START_TAG
1652 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001653 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001654 }
1655
1656 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001657 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001658 return null;
1659 }
1660
1661 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001662 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1663 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001664 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001665 return null;
1666 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001667 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1668 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001669 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001670 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1671 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001672 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1673 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001674 restrictedProfileParentId = readIntAttribute(parser,
1675 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001676 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1677 if ("true".equals(valueString)) {
1678 partial = true;
1679 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001680 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1681 if ("true".equals(valueString)) {
1682 guestToRemove = true;
1683 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001684
Amith Yamasani12747872015-12-07 14:19:49 -08001685 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1686 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1687 if (seedAccountName != null || seedAccountType != null) {
1688 persistSeedData = true;
1689 }
1690
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001691 int outerDepth = parser.getDepth();
1692 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1693 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1694 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1695 continue;
1696 }
1697 String tag = parser.getName();
1698 if (TAG_NAME.equals(tag)) {
1699 type = parser.next();
1700 if (type == XmlPullParser.TEXT) {
1701 name = parser.getText();
1702 }
1703 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001704 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1705 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1706 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001707 } else if (TAG_ACCOUNT.equals(tag)) {
1708 type = parser.next();
1709 if (type == XmlPullParser.TEXT) {
1710 account = parser.getText();
1711 }
Amith Yamasani12747872015-12-07 14:19:49 -08001712 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1713 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1714 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001715 }
1716 }
1717 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001718
Amith Yamasani12747872015-12-07 14:19:49 -08001719 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001720 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001721 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001722 userInfo.creationTime = creationTime;
1723 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001724 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001725 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001726 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001727 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001728
1729 // Create the UserData object that's internal to this class
1730 UserData userData = new UserData();
1731 userData.info = userInfo;
1732 userData.account = account;
1733 userData.seedAccountName = seedAccountName;
1734 userData.seedAccountType = seedAccountType;
1735 userData.persistSeedData = persistSeedData;
1736 userData.seedAccountOptions = seedAccountOptions;
1737
Makoto Onuki068c54a2015-10-13 14:34:03 -07001738 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001739 mBaseUserRestrictions.put(id, baseRestrictions);
1740 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001741 }
Amith Yamasani12747872015-12-07 14:19:49 -08001742 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001743 } catch (IOException ioe) {
1744 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001745 } finally {
1746 if (fis != null) {
1747 try {
1748 fis.close();
1749 } catch (IOException e) {
1750 }
1751 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001752 }
1753 return null;
1754 }
1755
Amith Yamasani920ace02012-09-20 22:15:37 -07001756 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1757 String valueString = parser.getAttributeValue(null, attr);
1758 if (valueString == null) return defaultValue;
1759 try {
1760 return Integer.parseInt(valueString);
1761 } catch (NumberFormatException nfe) {
1762 return defaultValue;
1763 }
1764 }
1765
1766 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1767 String valueString = parser.getAttributeValue(null, attr);
1768 if (valueString == null) return defaultValue;
1769 try {
1770 return Long.parseLong(valueString);
1771 } catch (NumberFormatException nfe) {
1772 return defaultValue;
1773 }
1774 }
1775
Amith Yamasanib82add22013-07-09 11:24:44 -07001776 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001777 * Removes the app restrictions file for a specific package and user id, if it exists.
1778 */
1779 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1780 synchronized (mPackagesLock) {
1781 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001782 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001783 if (resFile.exists()) {
1784 resFile.delete();
1785 }
1786 }
1787 }
1788
Kenny Guya52dc3e2014-02-11 15:33:14 +00001789 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001790 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001791 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001792 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001793 }
1794
Amith Yamasani258848d2012-08-10 17:06:33 -07001795 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001796 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001797 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001798 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001799 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001800
Jessica Hummelbe81c802014-04-22 15:49:22 +01001801 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001802 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001803 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1804 return null;
1805 }
phweisse9c44062016-02-10 12:57:38 +01001806 return createUserInternalUnchecked(name, flags, parentId);
1807 }
1808
1809 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001810 if (ActivityManager.isLowRamDeviceStatic()) {
1811 return null;
1812 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001813 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001814 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001815 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001816 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001817 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001818 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001819 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001820 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001821 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001822 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001823 if (parentId != UserHandle.USER_NULL) {
1824 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001825 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001826 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001827 if (parent == null) return null;
1828 }
1829 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1830 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1831 return null;
1832 }
1833 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1834 // If we're not adding a guest user or a managed profile and the limit has
1835 // been reached, cannot add a user.
1836 return null;
1837 }
1838 // If we're adding a guest and there already exists one, bail.
1839 if (isGuest && findCurrentGuestUser() != null) {
1840 return null;
1841 }
1842 // In legacy mode, restricted profile's parent can only be the owner user
1843 if (isRestricted && !UserManager.isSplitSystemUser()
1844 && (parentId != UserHandle.USER_SYSTEM)) {
1845 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1846 return null;
1847 }
1848 if (isRestricted && UserManager.isSplitSystemUser()) {
1849 if (parent == null) {
1850 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1851 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001852 return null;
1853 }
Amith Yamasani12747872015-12-07 14:19:49 -08001854 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001855 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1856 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001857 return null;
1858 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001859 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01001860 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
1861 Log.e(LOG_TAG,
1862 "Ephemeral users are supported on split-system-user systems only.");
1863 return null;
1864 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001865 // In split system user mode, we assign the first human user the primary flag.
1866 // And if there is no device owner, we also assign the admin flag to primary user.
1867 if (UserManager.isSplitSystemUser()
1868 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1869 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001870 synchronized (mUsersLock) {
1871 if (!mIsDeviceManaged) {
1872 flags |= UserInfo.FLAG_ADMIN;
1873 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001874 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001875 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001876
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001877 userId = getNextAvailableId();
1878 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001879 boolean ephemeralGuests = Resources.getSystem()
1880 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001881
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001882 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001883 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1884 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1885 || (parent != null && parent.info.isEphemeral())) {
1886 flags |= UserInfo.FLAG_EPHEMERAL;
1887 }
1888
1889 userInfo = new UserInfo(userId, name, null, flags);
1890 userInfo.serialNumber = mNextSerialNumber++;
1891 long now = System.currentTimeMillis();
1892 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1893 userInfo.partial = true;
1894 userData = new UserData();
1895 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001896 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001897 }
1898 writeUserListLP();
1899 if (parent != null) {
1900 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001901 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1902 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001903 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001904 }
Amith Yamasani12747872015-12-07 14:19:49 -08001905 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001906 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001907 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1908 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001909 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001910 }
Amith Yamasani12747872015-12-07 14:19:49 -08001911 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001912 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001913 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001914 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001915 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001916 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkey47f71082016-02-01 17:03:54 -07001917 prepareUserStorage(userId, userInfo.serialNumber,
1918 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001919 mPm.createNewUser(userId);
1920 userInfo.partial = false;
1921 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001922 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001923 }
1924 updateUserIds();
1925 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001926 if (isGuest) {
1927 synchronized (mGuestRestrictions) {
1928 restrictions.putAll(mGuestRestrictions);
1929 }
1930 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001931 synchronized (mRestrictionsLock) {
1932 mBaseUserRestrictions.append(userId, restrictions);
1933 }
1934 mPm.newUserCreated(userId);
1935 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1936 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1937 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1938 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001939 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001940 } finally {
1941 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001942 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001943 return userInfo;
1944 }
1945
Amith Yamasani0b285492011-04-14 17:35:23 -07001946 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001947 * @hide
1948 */
Amith Yamasani12747872015-12-07 14:19:49 -08001949 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001950 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1951 checkManageUsersPermission("setupRestrictedProfile");
1952 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1953 if (user == null) {
1954 return null;
1955 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08001956 long identity = Binder.clearCallingIdentity();
1957 try {
1958 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1959 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1960 // the putIntForUser() will fail.
1961 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1962 android.provider.Settings.Secure.LOCATION_MODE,
1963 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1964 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1965 } finally {
1966 Binder.restoreCallingIdentity(identity);
1967 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001968 return user;
1969 }
1970
1971 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001972 * Find the current guest user. If the Guest user is partial,
1973 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001974 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001975 private UserInfo findCurrentGuestUser() {
1976 synchronized (mUsersLock) {
1977 final int size = mUsers.size();
1978 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001979 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001980 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1981 return user;
1982 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001983 }
1984 }
1985 return null;
1986 }
1987
1988 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001989 * Mark this guest user for deletion to allow us to create another guest
1990 * and switch to that user before actually removing this guest.
1991 * @param userHandle the userid of the current guest
1992 * @return whether the user could be marked for deletion
1993 */
Amith Yamasani12747872015-12-07 14:19:49 -08001994 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07001995 public boolean markGuestForDeletion(int userHandle) {
1996 checkManageUsersPermission("Only the system can remove users");
1997 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1998 UserManager.DISALLOW_REMOVE_USER, false)) {
1999 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2000 return false;
2001 }
2002
2003 long ident = Binder.clearCallingIdentity();
2004 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002005 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002006 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002007 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002008 userData = mUsers.get(userHandle);
2009 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002010 return false;
2011 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002012 }
Amith Yamasani12747872015-12-07 14:19:49 -08002013 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002014 return false;
2015 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002016 // We set this to a guest user that is to be removed. This is a temporary state
2017 // where we are allowed to add new Guest users, even if this one is still not
2018 // removed. This user will still show up in getUserInfo() calls.
2019 // If we don't get around to removing this Guest user, it will be purged on next
2020 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002021 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002022 // Mark it as disabled, so that it isn't returned any more when
2023 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002024 userData.info.flags |= UserInfo.FLAG_DISABLED;
2025 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002026 }
2027 } finally {
2028 Binder.restoreCallingIdentity(ident);
2029 }
2030 return true;
2031 }
2032
2033 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002034 * Removes a user and all data directories created for that user. This method should be called
2035 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002036 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002037 */
Amith Yamasani12747872015-12-07 14:19:49 -08002038 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002039 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002040 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002041 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2042 UserManager.DISALLOW_REMOVE_USER, false)) {
2043 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2044 return false;
2045 }
2046
Kenny Guyee58b4f2014-05-23 15:19:53 +01002047 long ident = Binder.clearCallingIdentity();
2048 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002049 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002050 int currentUser = ActivityManager.getCurrentUser();
2051 if (currentUser == userHandle) {
2052 Log.w(LOG_TAG, "Current user cannot be removed");
2053 return false;
2054 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002055 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002056 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002057 userData = mUsers.get(userHandle);
2058 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002059 return false;
2060 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002061
Fyodor Kupolov82402752015-10-28 14:54:51 -07002062 // We remember deleted user IDs to prevent them from being
2063 // reused during the current boot; they can still be reused
2064 // after a reboot.
2065 mRemovingUserIds.put(userHandle, true);
2066 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002067
Kenny Guyee58b4f2014-05-23 15:19:53 +01002068 try {
2069 mAppOpsService.removeUser(userHandle);
2070 } catch (RemoteException e) {
2071 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2072 }
2073 // Set this to a partially created user, so that the user will be purged
2074 // on next startup, in case the runtime stops now before stopping and
2075 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002076 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002077 // Mark it as disabled, so that it isn't returned any more when
2078 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002079 userData.info.flags |= UserInfo.FLAG_DISABLED;
2080 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002081 }
2082
Amith Yamasani12747872015-12-07 14:19:49 -08002083 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2084 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002085 // Send broadcast to notify system that the user removed was a
2086 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002087 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002088 }
2089
2090 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2091 int res;
2092 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002093 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2094 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002095 @Override
2096 public void userStopped(int userId) {
2097 finishRemoveUser(userId);
2098 }
2099 @Override
2100 public void userStopAborted(int userId) {
2101 }
2102 });
2103 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002104 return false;
2105 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002106 return res == ActivityManager.USER_OP_SUCCESS;
2107 } finally {
2108 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002109 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002110 }
2111
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002112 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002113 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002114 // Let other services shutdown any activity and clean up their state before completely
2115 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002116 long ident = Binder.clearCallingIdentity();
2117 try {
2118 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2119 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002120 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2121 android.Manifest.permission.MANAGE_USERS,
2122
2123 new BroadcastReceiver() {
2124 @Override
2125 public void onReceive(Context context, Intent intent) {
2126 if (DBG) {
2127 Slog.i(LOG_TAG,
2128 "USER_REMOVED broadcast sent, cleaning up user data "
2129 + userHandle);
2130 }
2131 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002132 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002133 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002134 // Clean up any ActivityManager state
2135 LocalServices.getService(ActivityManagerInternal.class)
2136 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002137 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002138 }
2139 }.start();
2140 }
2141 },
2142
2143 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002144 } finally {
2145 Binder.restoreCallingIdentity(ident);
2146 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002147 }
2148
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002149 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002150 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002151 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002152 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002153
2154 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002155 synchronized (mUsersLock) {
2156 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002157 mIsUserManaged.delete(userHandle);
2158 }
2159 synchronized (mRestrictionsLock) {
2160 mBaseUserRestrictions.remove(userHandle);
2161 mAppliedUserRestrictions.remove(userHandle);
2162 mCachedEffectiveUserRestrictions.remove(userHandle);
2163 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002164 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002165 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002166 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002167 userFile.delete();
2168 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002169 synchronized (mPackagesLock) {
2170 writeUserListLP();
2171 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002172 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002173 File userDir = Environment.getUserSystemDirectory(userHandle);
2174 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2175 if (userDir.renameTo(renamedUserDir)) {
2176 removeDirectoryRecursive(renamedUserDir);
2177 } else {
2178 removeDirectoryRecursive(userDir);
2179 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002180 }
2181
Amith Yamasani61f57372012-08-31 12:12:28 -07002182 private void removeDirectoryRecursive(File parent) {
2183 if (parent.isDirectory()) {
2184 String[] files = parent.list();
2185 for (String filename : files) {
2186 File child = new File(parent, filename);
2187 removeDirectoryRecursive(child);
2188 }
2189 }
2190 parent.delete();
2191 }
2192
Kenny Guyf8d3a232014-05-15 16:09:52 +01002193 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002194 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002195 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2196 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002197 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002198 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002199 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002200 }
2201
Amith Yamasani2a003292012-08-14 18:25:45 -07002202 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002203 public Bundle getApplicationRestrictions(String packageName) {
2204 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2205 }
2206
2207 @Override
2208 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002209 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002210 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002211 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002212 }
2213 synchronized (mPackagesLock) {
2214 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002215 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002216 }
2217 }
2218
2219 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002220 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002221 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002222 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002223 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002224 if (restrictions == null || restrictions.isEmpty()) {
2225 cleanAppRestrictionsForPackage(packageName, userId);
2226 } else {
2227 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002228 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002229 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002230 }
Robin Lee66e5d962014-04-09 16:44:21 +01002231
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002232 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2233 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2234 changeIntent.setPackage(packageName);
2235 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2236 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002237 }
2238
2239 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002240 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002241 try {
2242 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002243 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002244 } catch (NameNotFoundException nnfe) {
2245 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002246 } finally {
2247 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002248 }
2249 }
2250
Fyodor Kupolov82402752015-10-28 14:54:51 -07002251 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002252 AtomicFile restrictionsFile =
2253 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2254 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002255 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002256 }
2257
2258 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002259 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002260 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002261 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002262 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002263 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002264 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002265
2266 FileInputStream fis = null;
2267 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002268 fis = restrictionsFile.openRead();
2269 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002270 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002271 XmlUtils.nextElement(parser);
2272 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002273 Slog.e(LOG_TAG, "Unable to read restrictions file "
2274 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002275 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002276 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002277 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2278 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002279 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002280 } catch (IOException|XmlPullParserException e) {
2281 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002282 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002283 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002284 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002285 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002286 }
2287
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002288 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2289 XmlPullParser parser) throws XmlPullParserException, IOException {
2290 int type = parser.getEventType();
2291 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2292 String key = parser.getAttributeValue(null, ATTR_KEY);
2293 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2294 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2295 if (multiple != null) {
2296 values.clear();
2297 int count = Integer.parseInt(multiple);
2298 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2299 if (type == XmlPullParser.START_TAG
2300 && parser.getName().equals(TAG_VALUE)) {
2301 values.add(parser.nextText().trim());
2302 count--;
2303 }
2304 }
2305 String [] valueStrings = new String[values.size()];
2306 values.toArray(valueStrings);
2307 restrictions.putStringArray(key, valueStrings);
2308 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2309 restrictions.putBundle(key, readBundleEntry(parser, values));
2310 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2311 final int outerDepth = parser.getDepth();
2312 ArrayList<Bundle> bundleList = new ArrayList<>();
2313 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2314 Bundle childBundle = readBundleEntry(parser, values);
2315 bundleList.add(childBundle);
2316 }
2317 restrictions.putParcelableArray(key,
2318 bundleList.toArray(new Bundle[bundleList.size()]));
2319 } else {
2320 String value = parser.nextText().trim();
2321 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2322 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2323 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2324 restrictions.putInt(key, Integer.parseInt(value));
2325 } else {
2326 restrictions.putString(key, value);
2327 }
2328 }
2329 }
2330 }
2331
2332 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2333 throws IOException, XmlPullParserException {
2334 Bundle childBundle = new Bundle();
2335 final int outerDepth = parser.getDepth();
2336 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2337 readEntry(childBundle, values, parser);
2338 }
2339 return childBundle;
2340 }
2341
Fyodor Kupolov82402752015-10-28 14:54:51 -07002342 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002343 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002344 AtomicFile restrictionsFile = new AtomicFile(
2345 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002346 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002347 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002348 }
2349
2350 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002351 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002352 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002353 try {
2354 fos = restrictionsFile.startWrite();
2355 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2356
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002357 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002358 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002359 serializer.startDocument(null, true);
2360 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2361
2362 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002363 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002364 serializer.endTag(null, TAG_RESTRICTIONS);
2365
2366 serializer.endDocument();
2367 restrictionsFile.finishWrite(fos);
2368 } catch (Exception e) {
2369 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002370 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2371 }
2372 }
2373
2374 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2375 throws IOException {
2376 for (String key : restrictions.keySet()) {
2377 Object value = restrictions.get(key);
2378 serializer.startTag(null, TAG_ENTRY);
2379 serializer.attribute(null, ATTR_KEY, key);
2380
2381 if (value instanceof Boolean) {
2382 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2383 serializer.text(value.toString());
2384 } else if (value instanceof Integer) {
2385 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2386 serializer.text(value.toString());
2387 } else if (value == null || value instanceof String) {
2388 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2389 serializer.text(value != null ? (String) value : "");
2390 } else if (value instanceof Bundle) {
2391 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2392 writeBundle((Bundle) value, serializer);
2393 } else if (value instanceof Parcelable[]) {
2394 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2395 Parcelable[] array = (Parcelable[]) value;
2396 for (Parcelable parcelable : array) {
2397 if (!(parcelable instanceof Bundle)) {
2398 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2399 }
2400 serializer.startTag(null, TAG_ENTRY);
2401 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2402 writeBundle((Bundle) parcelable, serializer);
2403 serializer.endTag(null, TAG_ENTRY);
2404 }
2405 } else {
2406 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2407 String[] values = (String[]) value;
2408 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2409 for (String choice : values) {
2410 serializer.startTag(null, TAG_VALUE);
2411 serializer.text(choice != null ? choice : "");
2412 serializer.endTag(null, TAG_VALUE);
2413 }
2414 }
2415 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002416 }
2417 }
2418
2419 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002420 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002421 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002422 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002423 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002424 }
2425 }
2426
2427 @Override
2428 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002429 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002430 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002431 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002432 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002433 }
2434 // Not found
2435 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002436 }
2437 }
2438
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002439 @Override
2440 public long getUserCreationTime(int userHandle) {
2441 int callingUserId = UserHandle.getCallingUserId();
2442 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002443 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002444 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002445 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002446 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002447 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002448 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002449 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002450 }
2451 }
2452 }
2453 if (userInfo == null) {
2454 throw new SecurityException("userHandle can only be the calling user or a managed "
2455 + "profile associated with this user");
2456 }
2457 return userInfo.creationTime;
2458 }
2459
Amith Yamasani0b285492011-04-14 17:35:23 -07002460 /**
2461 * Caches the list of user ids in an array, adjusting the array size when necessary.
2462 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002463 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002464 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002465 synchronized (mUsersLock) {
2466 final int userSize = mUsers.size();
2467 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002468 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002469 num++;
2470 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002471 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002472 final int[] newUsers = new int[num];
2473 int n = 0;
2474 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002475 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002476 newUsers[n++] = mUsers.keyAt(i);
2477 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002478 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002479 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002480 }
2481 }
2482
2483 /**
Jeff Sharkey47f71082016-02-01 17:03:54 -07002484 * Prepare storage areas for given user on all mounted devices.
2485 */
2486 private void prepareUserStorage(int userId, int userSerial, int flags) {
2487 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2488 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
2489 final String volumeUuid = vol.getFsUuid();
2490 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
2491 }
2492 }
2493
2494 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002495 * Called right before a user is started. This gives us a chance to prepare
2496 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002497 */
2498 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002499 final int userSerial = getUserSerialNumber(userId);
2500 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2501 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002502
2503 if (userId != UserHandle.USER_SYSTEM) {
2504 synchronized (mRestrictionsLock) {
2505 applyUserRestrictionsLR(userId);
2506 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002507 }
2508 }
2509
2510 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002511 * Called right before a user is unlocked. This gives us a chance to prepare
2512 * app storage.
2513 */
2514 public void onBeforeUnlockUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002515 final int userSerial = getUserSerialNumber(userId);
2516 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
2517 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002518 }
2519
2520 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002521 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002522 * @param userId the user that was just foregrounded
2523 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002524 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002525 UserData userData = getUserDataNoChecks(userId);
2526 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002527 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2528 return;
2529 }
2530 long now = System.currentTimeMillis();
2531 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002532 userData.info.lastLoggedInTime = now;
2533 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002534 }
2535 }
2536
2537 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002538 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002539 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2540 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002541 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002542 private int getNextAvailableId() {
2543 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002544 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002545 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002546 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002547 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002548 }
2549 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002550 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002551 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002552 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002553 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002554
Amith Yamasanifc95e702013-09-26 13:20:17 -07002555 private String packageToRestrictionsFileName(String packageName) {
2556 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2557 }
2558
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002559 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002560 * Enforce that serial number stored in user directory inode matches the
2561 * given expected value. Gracefully sets the serial number if currently
2562 * undefined.
2563 *
2564 * @throws IOException when problem extracting serial number, or serial
2565 * number is mismatched.
2566 */
2567 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2568 final int foundSerial = getSerialNumber(file);
2569 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2570
2571 if (foundSerial == -1) {
2572 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2573 try {
2574 setSerialNumber(file, serialNumber);
2575 } catch (IOException e) {
2576 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2577 }
2578
2579 } else if (foundSerial != serialNumber) {
2580 throw new IOException("Found serial number " + foundSerial
2581 + " doesn't match expected " + serialNumber);
2582 }
2583 }
2584
2585 /**
2586 * Set serial number stored in user directory inode.
2587 *
2588 * @throws IOException if serial number was already set
2589 */
2590 private static void setSerialNumber(File file, int serialNumber)
2591 throws IOException {
2592 try {
2593 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2594 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2595 } catch (ErrnoException e) {
2596 throw e.rethrowAsIOException();
2597 }
2598 }
2599
2600 /**
2601 * Return serial number stored in user directory inode.
2602 *
2603 * @return parsed serial number, or -1 if not set
2604 */
2605 private static int getSerialNumber(File file) throws IOException {
2606 try {
2607 final byte[] buf = new byte[256];
2608 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2609 final String serial = new String(buf, 0, len);
2610 try {
2611 return Integer.parseInt(serial);
2612 } catch (NumberFormatException e) {
2613 throw new IOException("Bad serial number: " + serial);
2614 }
2615 } catch (ErrnoException e) {
2616 if (e.errno == OsConstants.ENODATA) {
2617 return -1;
2618 } else {
2619 throw e.rethrowAsIOException();
2620 }
2621 }
2622 }
2623
Amith Yamasani920ace02012-09-20 22:15:37 -07002624 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002625 public void setSeedAccountData(int userId, String accountName, String accountType,
2626 PersistableBundle accountOptions, boolean persist) {
2627 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2628 synchronized (mPackagesLock) {
2629 final UserData userData;
2630 synchronized (mUsersLock) {
2631 userData = getUserDataLU(userId);
2632 if (userData == null) {
2633 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2634 return;
2635 }
2636 userData.seedAccountName = accountName;
2637 userData.seedAccountType = accountType;
2638 userData.seedAccountOptions = accountOptions;
2639 userData.persistSeedData = persist;
2640 }
2641 if (persist) {
2642 writeUserLP(userData);
2643 }
2644 }
2645 }
2646
2647 @Override
2648 public String getSeedAccountName() throws RemoteException {
2649 checkManageUsersPermission("Cannot get seed account information");
2650 synchronized (mUsersLock) {
2651 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2652 return userData.seedAccountName;
2653 }
2654 }
2655
2656 @Override
2657 public String getSeedAccountType() throws RemoteException {
2658 checkManageUsersPermission("Cannot get seed account information");
2659 synchronized (mUsersLock) {
2660 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2661 return userData.seedAccountType;
2662 }
2663 }
2664
2665 @Override
2666 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2667 checkManageUsersPermission("Cannot get seed account information");
2668 synchronized (mUsersLock) {
2669 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2670 return userData.seedAccountOptions;
2671 }
2672 }
2673
2674 @Override
2675 public void clearSeedAccountData() throws RemoteException {
2676 checkManageUsersPermission("Cannot clear seed account information");
2677 synchronized (mPackagesLock) {
2678 UserData userData;
2679 synchronized (mUsersLock) {
2680 userData = getUserDataLU(UserHandle.getCallingUserId());
2681 if (userData == null) return;
2682 userData.clearSeedAccountData();
2683 }
2684 writeUserLP(userData);
2685 }
2686 }
2687
2688 @Override
2689 public boolean someUserHasSeedAccount(String accountName, String accountType)
2690 throws RemoteException {
2691 checkManageUsersPermission("Cannot check seed account information");
2692 synchronized (mUsersLock) {
2693 final int userSize = mUsers.size();
2694 for (int i = 0; i < userSize; i++) {
2695 final UserData data = mUsers.valueAt(i);
2696 if (data.info.isInitialized()) continue;
2697 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2698 continue;
2699 }
2700 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2701 continue;
2702 }
2703 return true;
2704 }
2705 }
2706 return false;
2707 }
2708
2709 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002710 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2711 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2712 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2713 }
2714
2715 int onShellCommand(Shell shell, String cmd) {
2716 if (cmd == null) {
2717 return shell.handleDefaultCommands(cmd);
2718 }
2719
2720 final PrintWriter pw = shell.getOutPrintWriter();
2721 try {
2722 switch(cmd) {
2723 case "list":
2724 return runList(pw);
2725 }
2726 } catch (RemoteException e) {
2727 pw.println("Remote exception: " + e);
2728 }
2729 return -1;
2730 }
2731
2732 private int runList(PrintWriter pw) throws RemoteException {
2733 final IActivityManager am = ActivityManagerNative.getDefault();
2734 final List<UserInfo> users = getUsers(false);
2735 if (users == null) {
2736 pw.println("Error: couldn't get users");
2737 return 1;
2738 } else {
2739 pw.println("Users:");
2740 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002741 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002742 pw.println("\t" + users.get(i).toString() + running);
2743 }
2744 return 0;
2745 }
2746 }
2747
2748 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002749 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2750 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2751 != PackageManager.PERMISSION_GRANTED) {
2752 pw.println("Permission Denial: can't dump UserManager from from pid="
2753 + Binder.getCallingPid()
2754 + ", uid=" + Binder.getCallingUid()
2755 + " without permission "
2756 + android.Manifest.permission.DUMP);
2757 return;
2758 }
2759
2760 long now = System.currentTimeMillis();
2761 StringBuilder sb = new StringBuilder();
2762 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002763 synchronized (mUsersLock) {
2764 pw.println("Users:");
2765 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002766 UserData userData = mUsers.valueAt(i);
2767 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002768 continue;
2769 }
Amith Yamasani12747872015-12-07 14:19:49 -08002770 UserInfo userInfo = userData.info;
2771 final int userId = userInfo.id;
2772 pw.print(" "); pw.print(userInfo);
2773 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002774 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002775 pw.print(" <removing> ");
2776 }
Amith Yamasani12747872015-12-07 14:19:49 -08002777 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002778 pw.print(" <partial>");
2779 }
2780 pw.println();
2781 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002782 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002783 pw.println("<unknown>");
2784 } else {
2785 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002786 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002787 sb.append(" ago");
2788 pw.println(sb);
2789 }
2790 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002791 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002792 pw.println("<unknown>");
2793 } else {
2794 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002795 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002796 sb.append(" ago");
2797 pw.println(sb);
2798 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002799 pw.print(" Has profile owner: ");
2800 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002801 pw.println(" Restrictions:");
2802 synchronized (mRestrictionsLock) {
2803 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002804 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002805 pw.println(" Device policy local restrictions:");
2806 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002807 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002808 pw.println(" Effective restrictions:");
2809 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002810 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002811 }
Amith Yamasani12747872015-12-07 14:19:49 -08002812
2813 if (userData.account != null) {
2814 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002815 pw.println();
2816 }
Amith Yamasani12747872015-12-07 14:19:49 -08002817
2818 if (userData.seedAccountName != null) {
2819 pw.print(" Seed account name: " + userData.seedAccountName);
2820 pw.println();
2821 if (userData.seedAccountType != null) {
2822 pw.print(" account type: " + userData.seedAccountType);
2823 pw.println();
2824 }
2825 if (userData.seedAccountOptions != null) {
2826 pw.print(" account options exist");
2827 pw.println();
2828 }
2829 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002830 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002831 }
Amith Yamasani12747872015-12-07 14:19:49 -08002832 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002833 pw.println(" Device policy global restrictions:");
2834 synchronized (mRestrictionsLock) {
2835 UserRestrictionsUtils
2836 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2837 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002838 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002839 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002840 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002841 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002842 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002843 synchronized (mUsersLock) {
2844 pw.println();
2845 pw.println(" Device managed: " + mIsDeviceManaged);
2846 }
Amith Yamasani12747872015-12-07 14:19:49 -08002847 // Dump some capabilities
2848 pw.println();
2849 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2850 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002851 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2852 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002853 }
2854 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002855
2856 final class MainHandler extends Handler {
2857
2858 @Override
2859 public void handleMessage(Message msg) {
2860 switch (msg.what) {
2861 case WRITE_USER_MSG:
2862 removeMessages(WRITE_USER_MSG, msg.obj);
2863 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002864 int userId = ((UserData) msg.obj).info.id;
2865 UserData userData = getUserDataNoChecks(userId);
2866 if (userData != null) {
2867 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002868 }
2869 }
2870 }
2871 }
2872 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002873
2874 /**
2875 * @param userId
2876 * @return whether the user has been initialized yet
2877 */
2878 boolean isInitialized(int userId) {
2879 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2880 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002881
2882 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002883 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002884 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2885 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002886 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002887 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002888 }
2889
2890 @Override
2891 public Bundle getBaseUserRestrictions(int userId) {
2892 synchronized (mRestrictionsLock) {
2893 return mBaseUserRestrictions.get(userId);
2894 }
2895 }
2896
2897 @Override
2898 public void setBaseUserRestrictionsByDpmsForMigration(
2899 int userId, Bundle baseRestrictions) {
2900 synchronized (mRestrictionsLock) {
2901 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002902 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002903 }
2904
Amith Yamasani12747872015-12-07 14:19:49 -08002905 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002906 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002907 if (userData != null) {
2908 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002909 } else {
2910 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2911 }
2912 }
2913 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002914
2915 @Override
2916 public boolean getUserRestriction(int userId, String key) {
2917 return getUserRestrictions(userId).getBoolean(key);
2918 }
2919
2920 @Override
2921 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2922 synchronized (mUserRestrictionsListeners) {
2923 mUserRestrictionsListeners.add(listener);
2924 }
2925 }
2926
2927 @Override
2928 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2929 synchronized (mUserRestrictionsListeners) {
2930 mUserRestrictionsListeners.remove(listener);
2931 }
2932 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002933
2934 @Override
2935 public void setDeviceManaged(boolean isManaged) {
2936 synchronized (mUsersLock) {
2937 mIsDeviceManaged = isManaged;
2938 }
2939 }
2940
2941 @Override
2942 public void setUserManaged(int userId, boolean isManaged) {
2943 synchronized (mUsersLock) {
2944 mIsUserManaged.put(userId, isManaged);
2945 }
2946 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01002947
2948 @Override
2949 public void setUserIcon(int userId, Bitmap bitmap) {
2950 long ident = Binder.clearCallingIdentity();
2951 try {
2952 synchronized (mPackagesLock) {
2953 UserData userData = getUserDataNoChecks(userId);
2954 if (userData == null || userData.info.partial) {
2955 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
2956 return;
2957 }
2958 writeBitmapLP(userData.info, bitmap);
2959 writeUserLP(userData);
2960 }
2961 sendUserInfoChangedBroadcast(userId);
2962 } finally {
2963 Binder.restoreCallingIdentity(ident);
2964 }
2965 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002966
2967 @Override
2968 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
2969 synchronized (mUsersLock) {
2970 mForceEphemeralUsers = forceEphemeralUsers;
2971 }
2972 }
2973
2974 @Override
2975 public void removeAllUsers() {
2976 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
2977 // Remove the non-system users straight away.
2978 removeNonSystemUsers();
2979 } else {
2980 // Switch to the system user first and then remove the other users.
2981 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
2982 @Override
2983 public void onReceive(Context context, Intent intent) {
2984 int userId =
2985 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2986 if (userId != UserHandle.USER_SYSTEM) {
2987 return;
2988 }
2989 mContext.unregisterReceiver(this);
2990 removeNonSystemUsers();
2991 }
2992 };
2993 IntentFilter userSwitchedFilter = new IntentFilter();
2994 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
2995 mContext.registerReceiver(
2996 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
2997
2998 // Switch to the system user.
2999 ActivityManager am =
3000 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3001 am.switchUser(UserHandle.USER_SYSTEM);
3002 }
3003 }
phweisse9c44062016-02-10 12:57:38 +01003004
3005 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003006 public void onEphemeralUserStop(int userId) {
3007 synchronized (mUsersLock) {
3008 UserInfo userInfo = getUserInfoLU(userId);
3009 if (userInfo != null && userInfo.isEphemeral()) {
3010 // Do not allow switching back to the ephemeral user again as the user is going
3011 // to be deleted.
3012 userInfo.flags |= UserInfo.FLAG_DISABLED;
3013 if (userInfo.isGuest()) {
3014 // Indicate that the guest will be deleted after it stops.
3015 userInfo.guestToRemove = true;
3016 }
3017 }
3018 }
3019 }
3020
3021 @Override
phweisse9c44062016-02-10 12:57:38 +01003022 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3023 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3024 // Keep this in sync with UserManager.createUser
3025 if (user != null && !user.isAdmin()) {
3026 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3027 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3028 }
3029 return user;
3030 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003031 }
3032
3033 /* Remove all the users except of the system one. */
3034 private void removeNonSystemUsers() {
3035 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3036 synchronized (mUsersLock) {
3037 final int userSize = mUsers.size();
3038 for (int i = 0; i < userSize; i++) {
3039 UserInfo ui = mUsers.valueAt(i).info;
3040 if (ui.id != UserHandle.USER_SYSTEM) {
3041 usersToRemove.add(ui);
3042 }
3043 }
3044 }
3045 for (UserInfo ui: usersToRemove) {
3046 removeUser(ui.id);
3047 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003048 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003049
3050 private class Shell extends ShellCommand {
3051 @Override
3052 public int onCommand(String cmd) {
3053 return onShellCommand(this, cmd);
3054 }
3055
3056 @Override
3057 public void onHelp() {
3058 final PrintWriter pw = getOutPrintWriter();
3059 pw.println("User manager (user) commands:");
3060 pw.println(" help");
3061 pw.println(" Print this help text.");
3062 pw.println("");
3063 pw.println(" list");
3064 pw.println(" Prints all users on the system.");
3065 }
3066 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003067
3068 private static void debug(String message) {
3069 Log.d(LOG_TAG, message +
3070 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3071 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003072}