blob: b7bc2e10b4c081a0e8889539b6cbade22628170e [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
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080019import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070020
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070023import android.app.ActivityManagerNative;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070024import android.app.ActivityThread;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070027import android.content.Context;
28import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070029import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070030import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080031import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070032import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070033import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070037import android.os.Environment;
38import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080039import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070042import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040043import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070044import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070045import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070046import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070047import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.util.Slog;
49import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070051import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070052import android.util.Xml;
53
Jason Monk62062992014-05-06 09:55:28 -040054import com.android.internal.app.IAppOpsService;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070055import com.android.internal.content.PackageMonitor;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080056import com.android.internal.util.ArrayUtils;
57import com.android.internal.util.FastXmlSerializer;
58
59import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61import org.xmlpull.v1.XmlSerializer;
62
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import java.io.BufferedOutputStream;
64import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070065import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070067import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070068import java.io.FileOutputStream;
69import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070070import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070071import java.security.MessageDigest;
72import java.security.NoSuchAlgorithmException;
73import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.util.ArrayList;
75import java.util.List;
76
Amith Yamasani258848d2012-08-10 17:06:33 -070077public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078
Amith Yamasani2a003292012-08-14 18:25:45 -070079 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070080
Amith Yamasani16389312012-10-17 21:20:14 -070081 private static final boolean DBG = false;
82
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070085 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070087 private static final String ATTR_CREATION_TIME = "created";
88 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070089 private static final String ATTR_SALT = "salt";
90 private static final String ATTR_PIN_HASH = "pinHash";
91 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
92 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070093 private static final String ATTR_SERIAL_NO = "serialNumber";
94 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070095 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070096 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010097 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800100 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800101 private static final String TAG_ENTRY = "entry";
102 private static final String TAG_VALUE = "value";
103 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700104 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800105 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700107 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
108 private static final String ATTR_TYPE_STRING = "s";
109 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700110 private static final String ATTR_TYPE_INTEGER = "i";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700111
Amith Yamasani0b285492011-04-14 17:35:23 -0700112 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700114 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800116 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700117 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800118
Amith Yamasani634cf312012-10-04 17:34:21 -0700119 private static final int MIN_USER_ID = 10;
120
Amith Yamasani5e486f52013-08-07 11:06:44 -0700121 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700122
Amith Yamasani920ace02012-09-20 22:15:37 -0700123 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
124
Amith Yamasani655d0e22013-06-12 14:19:10 -0700125 // Number of attempts before jumping to the next BACKOFF_TIMES slot
126 private static final int BACKOFF_INC_INTERVAL = 5;
127
128 // Amount of time to force the user to wait before entering the PIN again, after failing
129 // BACKOFF_INC_INTERVAL times.
130 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
131
Dianne Hackborn4428e172012-08-24 17:43:05 -0700132 private final Context mContext;
133 private final PackageManagerService mPm;
134 private final Object mInstallLock;
135 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800137 private final Handler mHandler;
138
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700139 private final File mUsersDir;
140 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700141 private final File mBaseUserPath;
142
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800143 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800144 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800145
Amith Yamasani655d0e22013-06-12 14:19:10 -0700146 class RestrictionsPinState {
147 long salt;
148 String pinHash;
149 int failedAttempts;
150 long lastAttemptTime;
151 }
152
153 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
154 new SparseArray<RestrictionsPinState>();
155
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800156 /**
157 * Set of user IDs being actively removed. Removed IDs linger in this set
158 * for several seconds to work around a VFS caching issue.
159 */
160 // @GuardedBy("mPackagesLock")
161 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700162
Amith Yamasani0b285492011-04-14 17:35:23 -0700163 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700164 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700165 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700166 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700167
Jason Monk62062992014-05-06 09:55:28 -0400168 private IAppOpsService mAppOpsService;
169
Amith Yamasani258848d2012-08-10 17:06:33 -0700170 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700171
Dianne Hackborn4428e172012-08-24 17:43:05 -0700172 public static UserManagerService getInstance() {
173 synchronized (UserManagerService.class) {
174 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700175 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700176 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700177
178 /**
179 * Available for testing purposes.
180 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700181 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700182 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700183 }
184
Dianne Hackborn4428e172012-08-24 17:43:05 -0700185 /**
186 * Called by package manager to create the service. This is closely
187 * associated with the package manager, and the given lock is the
188 * package manager's own lock.
189 */
190 UserManagerService(Context context, PackageManagerService pm,
191 Object installLock, Object packagesLock) {
192 this(context, pm, installLock, packagesLock,
193 Environment.getDataDirectory(),
194 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700195 }
196
Dianne Hackborn4428e172012-08-24 17:43:05 -0700197 /**
198 * Available for testing purposes.
199 */
200 private UserManagerService(Context context, PackageManagerService pm,
201 Object installLock, Object packagesLock,
202 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700203 mContext = context;
204 mPm = pm;
205 mInstallLock = installLock;
206 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800207 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700208 synchronized (mInstallLock) {
209 synchronized (mPackagesLock) {
210 mUsersDir = new File(dataDir, USER_INFO_DIR);
211 mUsersDir.mkdirs();
212 // Make zeroth user directory, for services to migrate their files to that location
213 File userZeroDir = new File(mUsersDir, "0");
214 userZeroDir.mkdirs();
215 mBaseUserPath = baseUserPath;
216 FileUtils.setPermissions(mUsersDir.toString(),
217 FileUtils.S_IRWXU|FileUtils.S_IRWXG
218 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
219 -1, -1);
220 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
221 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700222 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700223 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
224 for (int i = 0; i < mUsers.size(); i++) {
225 UserInfo ui = mUsers.valueAt(i);
226 if (ui.partial && i != 0) {
227 partials.add(ui);
228 }
229 }
230 for (int i = 0; i < partials.size(); i++) {
231 UserInfo ui = partials.get(i);
232 Slog.w(LOG_TAG, "Removing partially created user #" + i
233 + " (name=" + ui.name + ")");
234 removeUserStateLocked(ui.id);
235 }
236 sInstance = this;
237 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700238 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700239 }
240
241 void systemReady() {
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700242 mUserPackageMonitor.register(mContext, null, UserHandle.ALL, false);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700243 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400244 mAppOpsService = IAppOpsService.Stub.asInterface(
245 ServiceManager.getService(Context.APP_OPS_SERVICE));
246 for (int i = 0; i < mUserIds.length; ++i) {
247 try {
248 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
249 } catch (RemoteException e) {
250 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
251 }
252 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700253 }
254
255 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700256 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700257 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700258 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700259 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
260 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700261 UserInfo ui = mUsers.valueAt(i);
262 if (ui.partial) {
263 continue;
264 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800265 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700266 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700267 }
Amith Yamasani13593602012-03-22 16:16:17 -0700268 }
269 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700270 }
Amith Yamasani13593602012-03-22 16:16:17 -0700271 }
272
Amith Yamasani258848d2012-08-10 17:06:33 -0700273 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100274 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800275 if (userId != UserHandle.getCallingUserId()) {
276 checkManageUsersPermission("getting profiles related to user " + userId);
277 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700278 final long ident = Binder.clearCallingIdentity();
279 try {
280 synchronized (mPackagesLock) {
281 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100282 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700283 } finally {
284 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000285 }
286 }
287
Amith Yamasanibe465322014-04-24 13:45:17 -0700288 /** Assume permissions already checked and caller's identity cleared */
289 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700290 UserInfo user = getUserInfoLocked(userId);
291 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
292 for (int i = 0; i < mUsers.size(); i++) {
293 UserInfo profile = mUsers.valueAt(i);
294 if (!isProfileOf(user, profile)) {
295 continue;
296 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100297 if (enabledOnly && !profile.isEnabled()) {
298 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700299 }
300 users.add(profile);
301 }
302 return users;
303 }
304
Jessica Hummelbe81c802014-04-22 15:49:22 +0100305 @Override
306 public UserInfo getProfileParent(int userHandle) {
307 checkManageUsersPermission("get the profile parent");
308 synchronized (mPackagesLock) {
309 UserInfo profile = getUserInfoLocked(userHandle);
310 int parentUserId = profile.profileGroupId;
311 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
312 return null;
313 } else {
314 return getUserInfoLocked(parentUserId);
315 }
316 }
317 }
318
Kenny Guy2a764942014-04-02 13:29:20 +0100319 private boolean isProfileOf(UserInfo user, UserInfo profile) {
320 return user.id == profile.id ||
321 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
322 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000323 }
324
325 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100326 public void setUserEnabled(int userId) {
327 checkManageUsersPermission("enable user");
328 synchronized (mPackagesLock) {
329 UserInfo info = getUserInfoLocked(userId);
330 if (info != null && !info.isEnabled()) {
331 info.flags ^= UserInfo.FLAG_DISABLED;
332 writeUserLocked(info);
333 }
334 }
335 }
336
337 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700338 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700339 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700340 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700341 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700342 }
343 }
344
Amith Yamasani71e6c692013-03-24 17:39:28 -0700345 @Override
346 public boolean isRestricted() {
347 synchronized (mPackagesLock) {
348 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
349 }
350 }
351
Amith Yamasani195263742012-08-21 15:40:12 -0700352 /*
353 * Should be locked on mUsers before calling this.
354 */
355 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700356 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700357 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800358 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700359 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
360 return null;
361 }
362 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700363 }
364
Amith Yamasani13593602012-03-22 16:16:17 -0700365 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700366 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700367 return ArrayUtils.contains(mUserIds, userId);
368 }
369 }
370
Amith Yamasani258848d2012-08-10 17:06:33 -0700371 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700372 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700373 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700374 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700375 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700376 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700377 if (info == null || info.partial) {
378 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
379 return;
380 }
Amith Yamasani13593602012-03-22 16:16:17 -0700381 if (name != null && !name.equals(info.name)) {
382 info.name = name;
383 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700384 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700385 }
386 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700387 if (changed) {
388 sendUserInfoChangedBroadcast(userId);
389 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700390 }
391
Amith Yamasani258848d2012-08-10 17:06:33 -0700392 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700393 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700394 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700395 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700396 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700397 if (info == null || info.partial) {
398 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
399 return;
400 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700401 writeBitmapLocked(info, bitmap);
402 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700403 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700404 sendUserInfoChangedBroadcast(userId);
405 }
406
407 private void sendUserInfoChangedBroadcast(int userId) {
408 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
409 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
410 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700411 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700412 }
413
Amith Yamasani258848d2012-08-10 17:06:33 -0700414 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700415 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700416 checkManageUsersPermission("read users");
417 synchronized (mPackagesLock) {
418 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700419 if (info == null || info.partial) {
420 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
421 return null;
422 }
423 if (info.iconPath == null) {
424 return null;
425 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700426 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700427 }
428 }
429
430 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700431 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700432 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700433 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700434 if (mGuestEnabled != enable) {
435 mGuestEnabled = enable;
436 // Erase any guest user that currently exists
437 for (int i = 0; i < mUsers.size(); i++) {
438 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700439 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700440 if (!enable) {
441 removeUser(user.id);
442 }
443 return;
444 }
445 }
446 // No guest was found
447 if (enable) {
448 createUser("Guest", UserInfo.FLAG_GUEST);
449 }
450 }
451 }
452 }
453
454 @Override
455 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700456 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700457 return mGuestEnabled;
458 }
459 }
460
461 @Override
462 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700463 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700464 // TODO:
465 }
466
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700467 public void makeInitialized(int userId) {
468 checkManageUsersPermission("makeInitialized");
469 synchronized (mPackagesLock) {
470 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700471 if (info == null || info.partial) {
472 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
473 }
474 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700475 info.flags |= UserInfo.FLAG_INITIALIZED;
476 writeUserLocked(info);
477 }
478 }
479 }
480
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800481 @Override
482 public Bundle getUserRestrictions(int userId) {
483 // checkManageUsersPermission("getUserRestrictions");
484
485 synchronized (mPackagesLock) {
486 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700487 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800488 }
489 }
490
491 @Override
492 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700493 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700494 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800495
496 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700497 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800498 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400499 long token = Binder.clearCallingIdentity();
500 try {
501 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
502 } catch (RemoteException e) {
503 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
504 } finally {
505 Binder.restoreCallingIdentity(token);
506 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800507 writeUserLocked(mUsers.get(userId));
508 }
509 }
510
Amith Yamasani258848d2012-08-10 17:06:33 -0700511 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700512 * Check if we've hit the limit of how many users can be created.
513 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700514 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700515 int aliveUserCount = 0;
516 final int totalUserCount = mUsers.size();
517 // Skip over users being removed
518 for (int i = 0; i < totalUserCount; i++) {
519 UserInfo user = mUsers.valueAt(i);
520 if (!mRemovingUserIds.get(user.id)) {
521 aliveUserCount++;
522 }
523 }
524 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700525 }
526
527 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700528 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700529 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700530 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700531 *
532 * @param message used as message if SecurityException is thrown
533 * @throws SecurityException if the caller is not system or root
534 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700535 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700536 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700537 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400538 && ActivityManager.checkComponentPermission(
539 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700540 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
541 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
542 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400543 }
544
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700545 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700546 try {
547 File dir = new File(mUsersDir, Integer.toString(info.id));
548 File file = new File(dir, USER_PHOTO_FILENAME);
549 if (!dir.exists()) {
550 dir.mkdir();
551 FileUtils.setPermissions(
552 dir.getPath(),
553 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
554 -1, -1);
555 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700556 FileOutputStream os;
557 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700558 info.iconPath = file.getAbsolutePath();
559 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700560 try {
561 os.close();
562 } catch (IOException ioe) {
563 // What the ... !
564 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700565 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700566 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700567 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700568 }
569
Amith Yamasani0b285492011-04-14 17:35:23 -0700570 /**
571 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
572 * cache it elsewhere.
573 * @return the array of user ids.
574 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700575 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700576 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700577 return mUserIds;
578 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700579 }
580
Dianne Hackborn4428e172012-08-24 17:43:05 -0700581 int[] getUserIdsLPr() {
582 return mUserIds;
583 }
584
Amith Yamasani13593602012-03-22 16:16:17 -0700585 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700586 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700587 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700588 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700589 return;
590 }
591 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700592 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700593 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700594 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700595 XmlPullParser parser = Xml.newPullParser();
596 parser.setInput(fis, null);
597 int type;
598 while ((type = parser.next()) != XmlPullParser.START_TAG
599 && type != XmlPullParser.END_DOCUMENT) {
600 ;
601 }
602
603 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700604 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700605 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700606 return;
607 }
608
Amith Yamasani2a003292012-08-14 18:25:45 -0700609 mNextSerialNumber = -1;
610 if (parser.getName().equals(TAG_USERS)) {
611 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
612 if (lastSerialNumber != null) {
613 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
614 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700615 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
616 if (versionNumber != null) {
617 mUserVersion = Integer.parseInt(versionNumber);
618 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700619 }
620
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700621 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
622 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
623 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800624 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700625
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700626 if (user != null) {
627 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700628 if (user.isGuest()) {
629 mGuestEnabled = true;
630 }
631 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
632 mNextSerialNumber = user.id + 1;
633 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700634 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700635 }
636 }
Amith Yamasani13593602012-03-22 16:16:17 -0700637 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700638 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700639 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700640 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700641 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700642 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800643 } finally {
644 if (fis != null) {
645 try {
646 fis.close();
647 } catch (IOException e) {
648 }
649 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700650 }
651 }
652
Amith Yamasani6f34b412012-10-22 18:19:27 -0700653 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800654 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700655 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700656 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700657 int userVersion = mUserVersion;
658 if (userVersion < 1) {
659 // Assign a proper name for the owner, if not initialized correctly before
660 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
661 if ("Primary".equals(user.name)) {
662 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
663 writeUserLocked(user);
664 }
665 userVersion = 1;
666 }
667
Amith Yamasanibc9625052012-11-15 14:39:18 -0800668 if (userVersion < 2) {
669 // Owner should be marked as initialized
670 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
671 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
672 user.flags |= UserInfo.FLAG_INITIALIZED;
673 writeUserLocked(user);
674 }
675 userVersion = 2;
676 }
677
Amith Yamasani350962c2013-08-06 11:18:53 -0700678
Amith Yamasani5e486f52013-08-07 11:06:44 -0700679 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700680 userVersion = 4;
681 }
682
Amith Yamasani6f34b412012-10-22 18:19:27 -0700683 if (userVersion < USER_VERSION) {
684 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
685 + USER_VERSION);
686 } else {
687 mUserVersion = userVersion;
688 writeUserListLocked();
689 }
690 }
691
Amith Yamasani13593602012-03-22 16:16:17 -0700692 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700693 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800694 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700695 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700696 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700697 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700698 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400699 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800700
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500701 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800702 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
703
Amith Yamasani13593602012-03-22 16:16:17 -0700704 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700705
Amith Yamasani13593602012-03-22 16:16:17 -0700706 writeUserListLocked();
707 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700708 }
709
710 /*
711 * Writes the user file in this format:
712 *
713 * <user flags="20039023" id="0">
714 * <name>Primary</name>
715 * </user>
716 */
Amith Yamasani13593602012-03-22 16:16:17 -0700717 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700718 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700719 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700720 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700721 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700722 final BufferedOutputStream bos = new BufferedOutputStream(fos);
723
724 // XmlSerializer serializer = XmlUtils.serializerInstance();
725 final XmlSerializer serializer = new FastXmlSerializer();
726 serializer.setOutput(bos, "utf-8");
727 serializer.startDocument(null, true);
728 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
729
730 serializer.startTag(null, TAG_USER);
731 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700732 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700733 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700734 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
735 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
736 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700737 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
738 if (pinState != null) {
739 if (pinState.salt != 0) {
740 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
741 }
742 if (pinState.pinHash != null) {
743 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
744 }
745 if (pinState.failedAttempts != 0) {
746 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
747 Integer.toString(pinState.failedAttempts));
748 serializer.attribute(null, ATTR_LAST_RETRY_MS,
749 Long.toString(pinState.lastAttemptTime));
750 }
751 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700752 if (userInfo.iconPath != null) {
753 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
754 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700755 if (userInfo.partial) {
756 serializer.attribute(null, ATTR_PARTIAL, "true");
757 }
Kenny Guy2a764942014-04-02 13:29:20 +0100758 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
759 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
760 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000761 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700762
763 serializer.startTag(null, TAG_NAME);
764 serializer.text(userInfo.name);
765 serializer.endTag(null, TAG_NAME);
766
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800767 Bundle restrictions = mUserRestrictions.get(userInfo.id);
768 if (restrictions != null) {
769 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700770 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
771 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
772 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
773 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
774 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400775 writeBoolean(serializer, restrictions,
776 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
777 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
778 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400779 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
780 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Julia Reynoldsd46d0f92014-04-23 15:23:24 -0400781 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
782 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
783 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
784 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
785 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
786 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
787 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
788 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
789 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_APPS);
Emily Bernier394a6cd2014-05-07 12:49:20 -0400790 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
791 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
792 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani9f6c25f2014-05-16 14:49:15 -0700793 writeBoolean(serializer, restrictions, UserManager.DISALLOW_TELEPHONY);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800794 serializer.endTag(null, TAG_RESTRICTIONS);
795 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700796 serializer.endTag(null, TAG_USER);
797
798 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700799 userFile.finishWrite(fos);
800 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700801 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700802 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700803 }
804 }
805
806 /*
807 * Writes the user list file in this format:
808 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700809 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700810 * <user id="0"></user>
811 * <user id="2"></user>
812 * </users>
813 */
Amith Yamasani13593602012-03-22 16:16:17 -0700814 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700815 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700816 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700817 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700818 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700819 final BufferedOutputStream bos = new BufferedOutputStream(fos);
820
821 // XmlSerializer serializer = XmlUtils.serializerInstance();
822 final XmlSerializer serializer = new FastXmlSerializer();
823 serializer.setOutput(bos, "utf-8");
824 serializer.startDocument(null, true);
825 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
826
827 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700828 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700829 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700830
831 for (int i = 0; i < mUsers.size(); i++) {
832 UserInfo user = mUsers.valueAt(i);
833 serializer.startTag(null, TAG_USER);
834 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
835 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700836 }
837
838 serializer.endTag(null, TAG_USERS);
839
840 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700841 userListFile.finishWrite(fos);
842 } catch (Exception e) {
843 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700844 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700845 }
846 }
847
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800848 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700849 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700850 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700851 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700852 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700853 long creationTime = 0L;
854 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700855 long salt = 0L;
856 String pinHash = null;
857 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100858 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700859 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700860 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800861 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700862
863 FileInputStream fis = null;
864 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700865 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700866 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700867 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700868 XmlPullParser parser = Xml.newPullParser();
869 parser.setInput(fis, null);
870 int type;
871 while ((type = parser.next()) != XmlPullParser.START_TAG
872 && type != XmlPullParser.END_DOCUMENT) {
873 ;
874 }
875
876 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700877 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700878 return null;
879 }
880
881 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700882 int storedId = readIntAttribute(parser, ATTR_ID, -1);
883 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700884 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700885 return null;
886 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700887 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
888 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700889 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700890 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
891 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700892 salt = readLongAttribute(parser, ATTR_SALT, 0L);
893 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
894 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
895 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100896 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
897 UserInfo.NO_PROFILE_GROUP_ID);
898 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
899 // This attribute was added and renamed during development of L.
900 // TODO Remove upgrade path by 1st May 2014
901 profileGroupId = readIntAttribute(parser, "relatedGroupId",
902 UserInfo.NO_PROFILE_GROUP_ID);
903 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700904 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
905 if ("true".equals(valueString)) {
906 partial = true;
907 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700908
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800909 int outerDepth = parser.getDepth();
910 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
911 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
912 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
913 continue;
914 }
915 String tag = parser.getName();
916 if (TAG_NAME.equals(tag)) {
917 type = parser.next();
918 if (type == XmlPullParser.TEXT) {
919 name = parser.getText();
920 }
921 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700922 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
923 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
924 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
925 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
926 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400927 readBoolean(parser, restrictions,
928 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
929 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
930 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400931 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
932 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Julia Reynoldsd46d0f92014-04-23 15:23:24 -0400933 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
934 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
935 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
936 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
937 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
938 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
939 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
940 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
941 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_APPS);
Emily Bernier394a6cd2014-05-07 12:49:20 -0400942 readBoolean(parser, restrictions,
943 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
944 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
945 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani9f6c25f2014-05-16 14:49:15 -0700946 readBoolean(parser, restrictions, UserManager.DISALLOW_TELEPHONY);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700947 }
948 }
949 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700950
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700951 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700952 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700953 userInfo.creationTime = creationTime;
954 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700955 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100956 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800957 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700958 if (salt != 0L) {
959 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
960 if (pinState == null) {
961 pinState = new RestrictionsPinState();
962 mRestrictionsPinStates.put(id, pinState);
963 }
964 pinState.salt = salt;
965 pinState.pinHash = pinHash;
966 pinState.failedAttempts = failedAttempts;
967 pinState.lastAttemptTime = lastAttemptTime;
968 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700969 return userInfo;
970
971 } catch (IOException ioe) {
972 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800973 } finally {
974 if (fis != null) {
975 try {
976 fis.close();
977 } catch (IOException e) {
978 }
979 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700980 }
981 return null;
982 }
983
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800984 private void readBoolean(XmlPullParser parser, Bundle restrictions,
985 String restrictionKey) {
986 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700987 if (value != null) {
988 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
989 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800990 }
991
992 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
993 throws IOException {
994 if (restrictions.containsKey(restrictionKey)) {
995 xml.attribute(null, restrictionKey,
996 Boolean.toString(restrictions.getBoolean(restrictionKey)));
997 }
998 }
999
Amith Yamasani920ace02012-09-20 22:15:37 -07001000 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1001 String valueString = parser.getAttributeValue(null, attr);
1002 if (valueString == null) return defaultValue;
1003 try {
1004 return Integer.parseInt(valueString);
1005 } catch (NumberFormatException nfe) {
1006 return defaultValue;
1007 }
1008 }
1009
1010 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1011 String valueString = parser.getAttributeValue(null, attr);
1012 if (valueString == null) return defaultValue;
1013 try {
1014 return Long.parseLong(valueString);
1015 } catch (NumberFormatException nfe) {
1016 return defaultValue;
1017 }
1018 }
1019
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001020 private boolean isPackageInstalled(String pkg, int userId) {
1021 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1022 PackageManager.GET_UNINSTALLED_PACKAGES,
1023 userId);
1024 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1025 return false;
1026 }
1027 return true;
1028 }
1029
Amith Yamasanib82add22013-07-09 11:24:44 -07001030 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001031 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
1032 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -07001033 * Does not do any permissions checking.
1034 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001035 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001036 synchronized (mPackagesLock) {
1037 File dir = Environment.getUserSystemDirectory(userId);
1038 String[] files = dir.list();
1039 if (files == null) return;
1040 for (String fileName : files) {
1041 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1042 File resFile = new File(dir, fileName);
1043 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001044 if (all) {
1045 resFile.delete();
1046 } else {
Amith Yamasanifc95e702013-09-26 13:20:17 -07001047 String pkg = restrictionsFileNameToPackage(fileName);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001048 if (!isPackageInstalled(pkg, userId)) {
1049 resFile.delete();
1050 }
1051 }
Amith Yamasanib82add22013-07-09 11:24:44 -07001052 }
1053 }
1054 }
1055 }
1056 }
1057
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001058 /**
1059 * Removes the app restrictions file for a specific package and user id, if it exists.
1060 */
1061 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1062 synchronized (mPackagesLock) {
1063 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001064 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001065 if (resFile.exists()) {
1066 resFile.delete();
1067 }
1068 }
1069 }
1070
Kenny Guya52dc3e2014-02-11 15:33:14 +00001071 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001072 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001073 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001074 if (userId != UserHandle.USER_OWNER) {
1075 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001076 return null;
1077 }
Kenny Guy2a764942014-04-02 13:29:20 +01001078 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001079 }
1080
Amith Yamasani258848d2012-08-10 17:06:33 -07001081 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001082 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001083 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001084 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001085 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001086
Jessica Hummelbe81c802014-04-22 15:49:22 +01001087 private UserInfo createUserInternal(String name, int flags, int parentId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001088 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001089 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001090 try {
1091 synchronized (mInstallLock) {
1092 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001093 UserInfo parent = null;
1094 if (parentId != UserHandle.USER_NULL) {
1095 parent = getUserInfoLocked(parentId);
1096 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001097 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001098 if (isUserLimitReachedLocked()) return null;
1099 int userId = getNextAvailableIdLocked();
1100 userInfo = new UserInfo(userId, name, null, flags);
1101 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1102 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001103 long now = System.currentTimeMillis();
1104 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001105 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001106 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001107 mUsers.put(userId, userInfo);
1108 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001109 if (parent != null) {
1110 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1111 parent.profileGroupId = parent.id;
1112 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001113 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001114 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001115 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001116 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001117 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001118 userInfo.partial = false;
1119 writeUserLocked(userInfo);
1120 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001121 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001122 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001123 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001124 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001125 if (userInfo != null) {
1126 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1127 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1128 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1129 android.Manifest.permission.MANAGE_USERS);
1130 }
1131 } finally {
1132 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001133 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001134 return userInfo;
1135 }
1136
Amith Yamasani0b285492011-04-14 17:35:23 -07001137 /**
1138 * Removes a user and all data directories created for that user. This method should be called
1139 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001140 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001141 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001142 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001143 checkManageUsersPermission("Only the system can remove users");
Kenny Guyee58b4f2014-05-23 15:19:53 +01001144 long ident = Binder.clearCallingIdentity();
1145 try {
1146 final UserInfo user;
1147 synchronized (mPackagesLock) {
1148 user = mUsers.get(userHandle);
1149 if (userHandle == 0 || user == null) {
1150 return false;
1151 }
1152 mRemovingUserIds.put(userHandle, true);
1153 try {
1154 mAppOpsService.removeUser(userHandle);
1155 } catch (RemoteException e) {
1156 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1157 }
1158 // Set this to a partially created user, so that the user will be purged
1159 // on next startup, in case the runtime stops now before stopping and
1160 // removing the user completely.
1161 user.partial = true;
1162 // Mark it as disabled, so that it isn't returned any more when
1163 // profiles are queried.
1164 user.flags |= UserInfo.FLAG_DISABLED;
1165 writeUserLocked(user);
1166 }
1167
1168 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1169 && user.isManagedProfile()) {
1170 // Send broadcast to notify system that the user removed was a
1171 // managed user.
1172 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1173 }
1174
1175 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1176 int res;
1177 try {
1178 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1179 new IStopUserCallback.Stub() {
1180 @Override
1181 public void userStopped(int userId) {
1182 finishRemoveUser(userId);
1183 }
1184 @Override
1185 public void userStopAborted(int userId) {
1186 }
1187 });
1188 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001189 return false;
1190 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001191 return res == ActivityManager.USER_OP_SUCCESS;
1192 } finally {
1193 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001194 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001195 }
1196
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001197 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001198 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001199 // Let other services shutdown any activity and clean up their state before completely
1200 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001201 long ident = Binder.clearCallingIdentity();
1202 try {
1203 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1204 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001205 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1206 android.Manifest.permission.MANAGE_USERS,
1207
1208 new BroadcastReceiver() {
1209 @Override
1210 public void onReceive(Context context, Intent intent) {
1211 if (DBG) {
1212 Slog.i(LOG_TAG,
1213 "USER_REMOVED broadcast sent, cleaning up user data "
1214 + userHandle);
1215 }
1216 new Thread() {
1217 public void run() {
1218 synchronized (mInstallLock) {
1219 synchronized (mPackagesLock) {
1220 removeUserStateLocked(userHandle);
1221 }
1222 }
1223 }
1224 }.start();
1225 }
1226 },
1227
1228 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001229 } finally {
1230 Binder.restoreCallingIdentity(ident);
1231 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001232 }
1233
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001234 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001235 // Cleanup package manager settings
1236 mPm.cleanUpUserLILPw(userHandle);
1237
1238 // Remove this user from the list
1239 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001240
1241 // Have user ID linger for several seconds to let external storage VFS
1242 // cache entries expire. This must be greater than the 'entry_valid'
1243 // timeout used by the FUSE daemon.
1244 mHandler.postDelayed(new Runnable() {
1245 @Override
1246 public void run() {
1247 synchronized (mPackagesLock) {
1248 mRemovingUserIds.delete(userHandle);
1249 }
1250 }
1251 }, MINUTE_IN_MILLIS);
1252
Amith Yamasani655d0e22013-06-12 14:19:10 -07001253 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001254 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001255 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001256 userFile.delete();
1257 // Update the user list
1258 writeUserListLocked();
1259 updateUserIdsLocked();
1260 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1261 }
1262
Amith Yamasani61f57372012-08-31 12:12:28 -07001263 private void removeDirectoryRecursive(File parent) {
1264 if (parent.isDirectory()) {
1265 String[] files = parent.list();
1266 for (String filename : files) {
1267 File child = new File(parent, filename);
1268 removeDirectoryRecursive(child);
1269 }
1270 }
1271 parent.delete();
1272 }
1273
Kenny Guyf8d3a232014-05-15 16:09:52 +01001274 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001275 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001276 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1277 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001278 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1279 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001280 }
1281
Amith Yamasani2a003292012-08-14 18:25:45 -07001282 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001283 public Bundle getApplicationRestrictions(String packageName) {
1284 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1285 }
1286
1287 @Override
1288 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001289 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001290 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001291 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001292 }
1293 synchronized (mPackagesLock) {
1294 // Read the restrictions from XML
1295 return readApplicationRestrictionsLocked(packageName, userId);
1296 }
1297 }
1298
1299 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001300 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001301 int userId) {
1302 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001303 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001304 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001305 }
1306 synchronized (mPackagesLock) {
1307 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001308 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001309 }
Robin Lee66e5d962014-04-09 16:44:21 +01001310
1311 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1312 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1313 changeIntent.setPackage(packageName);
1314 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1315 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001316 }
1317
Amith Yamasani655d0e22013-06-12 14:19:10 -07001318 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001319 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001320 checkManageUsersPermission("Only system can modify the restrictions pin");
1321 int userId = UserHandle.getCallingUserId();
1322 synchronized (mPackagesLock) {
1323 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1324 if (pinState == null) {
1325 pinState = new RestrictionsPinState();
1326 }
1327 if (newPin == null) {
1328 pinState.salt = 0;
1329 pinState.pinHash = null;
1330 } else {
1331 try {
1332 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1333 } catch (NoSuchAlgorithmException e) {
1334 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1335 }
1336 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1337 pinState.failedAttempts = 0;
1338 }
1339 mRestrictionsPinStates.put(userId, pinState);
1340 writeUserLocked(mUsers.get(userId));
1341 }
1342 return true;
1343 }
1344
1345 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001346 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001347 checkManageUsersPermission("Only system can verify the restrictions pin");
1348 int userId = UserHandle.getCallingUserId();
1349 synchronized (mPackagesLock) {
1350 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1351 // If there's no pin set, return error code
1352 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1353 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1354 } else if (pin == null) {
1355 // If just checking if user can be prompted, return remaining time
1356 int waitTime = getRemainingTimeForPinAttempt(pinState);
1357 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1358 return waitTime;
1359 } else {
1360 int waitTime = getRemainingTimeForPinAttempt(pinState);
1361 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1362 if (waitTime > 0) {
1363 return waitTime;
1364 }
1365 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1366 pinState.failedAttempts = 0;
1367 writeUserLocked(mUsers.get(userId));
1368 return UserManager.PIN_VERIFICATION_SUCCESS;
1369 } else {
1370 pinState.failedAttempts++;
1371 pinState.lastAttemptTime = System.currentTimeMillis();
1372 writeUserLocked(mUsers.get(userId));
1373 return waitTime;
1374 }
1375 }
1376 }
1377 }
1378
1379 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1380 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1381 BACKOFF_TIMES.length - 1);
1382 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1383 BACKOFF_TIMES[backoffIndex] : 0;
1384 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1385 0);
1386 }
1387
1388 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001389 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001390 int userId = UserHandle.getCallingUserId();
1391 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001392 return hasRestrictionsPinLocked(userId);
1393 }
1394 }
1395
1396 private boolean hasRestrictionsPinLocked(int userId) {
1397 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1398 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1399 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001400 }
1401 return true;
1402 }
1403
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001404 @Override
1405 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001406 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001407 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001408 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001409 }
1410
Amith Yamasani5e486f52013-08-07 11:06:44 -07001411 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001412 synchronized (mPackagesLock) {
1413 // Remove all user restrictions
1414 setUserRestrictions(new Bundle(), userHandle);
1415 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001416 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001417 // Remove any app restrictions
1418 cleanAppRestrictions(userHandle, true);
1419 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001420 if (unblockApps) {
1421 unblockAllAppsForUser(userHandle);
1422 }
1423 }
1424
1425 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001426 mHandler.post(new Runnable() {
1427 @Override
1428 public void run() {
1429 List<ApplicationInfo> apps =
1430 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1431 userHandle).getList();
1432 final long ident = Binder.clearCallingIdentity();
1433 try {
1434 for (ApplicationInfo appInfo : apps) {
1435 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1436 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1437 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1438 userHandle);
1439 }
1440 }
1441 } finally {
1442 Binder.restoreCallingIdentity(ident);
1443 }
1444 }
1445 });
1446 }
1447
Amith Yamasani655d0e22013-06-12 14:19:10 -07001448 /*
1449 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1450 * Not the most secure, but it is at least a second level of protection. First level is that
1451 * the file is in a location only readable by the system process.
1452 * @param password the password.
1453 * @param salt the randomly generated salt
1454 * @return the hash of the pattern in a String.
1455 */
1456 private String passwordToHash(String password, long salt) {
1457 if (password == null) {
1458 return null;
1459 }
1460 String algo = null;
1461 String hashed = salt + password;
1462 try {
1463 byte[] saltedPassword = (password + salt).getBytes();
1464 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1465 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1466 hashed = toHex(sha1) + toHex(md5);
1467 } catch (NoSuchAlgorithmException e) {
1468 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1469 }
1470 return hashed;
1471 }
1472
1473 private static String toHex(byte[] ary) {
1474 final String hex = "0123456789ABCDEF";
1475 String ret = "";
1476 for (int i = 0; i < ary.length; i++) {
1477 ret += hex.charAt((ary[i] >> 4) & 0xf);
1478 ret += hex.charAt(ary[i] & 0xf);
1479 }
1480 return ret;
1481 }
1482
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001483 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001484 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001485 try {
1486 return mContext.getPackageManager().getApplicationInfo(packageName,
1487 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1488 } catch (NameNotFoundException nnfe) {
1489 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001490 } finally {
1491 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001492 }
1493 }
1494
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001495 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001496 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001497 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001498 final ArrayList<String> values = new ArrayList<String>();
1499
1500 FileInputStream fis = null;
1501 try {
1502 AtomicFile restrictionsFile =
1503 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001504 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001505 fis = restrictionsFile.openRead();
1506 XmlPullParser parser = Xml.newPullParser();
1507 parser.setInput(fis, null);
1508 int type;
1509 while ((type = parser.next()) != XmlPullParser.START_TAG
1510 && type != XmlPullParser.END_DOCUMENT) {
1511 ;
1512 }
1513
1514 if (type != XmlPullParser.START_TAG) {
1515 Slog.e(LOG_TAG, "Unable to read restrictions file "
1516 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001517 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001518 }
1519
1520 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1521 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1522 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001523 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001524 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1525 if (multiple != null) {
1526 int count = Integer.parseInt(multiple);
1527 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1528 if (type == XmlPullParser.START_TAG
1529 && parser.getName().equals(TAG_VALUE)) {
1530 values.add(parser.nextText().trim());
1531 count--;
1532 }
1533 }
1534 String [] valueStrings = new String[values.size()];
1535 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001536 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001537 } else {
1538 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001539 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1540 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1541 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1542 restrictions.putInt(key, Integer.parseInt(value));
1543 } else {
1544 restrictions.putString(key, value);
1545 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001546 }
1547 }
1548 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001549 } catch (IOException ioe) {
1550 } catch (XmlPullParserException pe) {
1551 } finally {
1552 if (fis != null) {
1553 try {
1554 fis.close();
1555 } catch (IOException e) {
1556 }
1557 }
1558 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001559 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001560 }
1561
1562 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001563 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001564 FileOutputStream fos = null;
1565 AtomicFile restrictionsFile = new AtomicFile(
1566 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001567 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001568 try {
1569 fos = restrictionsFile.startWrite();
1570 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1571
1572 // XmlSerializer serializer = XmlUtils.serializerInstance();
1573 final XmlSerializer serializer = new FastXmlSerializer();
1574 serializer.setOutput(bos, "utf-8");
1575 serializer.startDocument(null, true);
1576 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1577
1578 serializer.startTag(null, TAG_RESTRICTIONS);
1579
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001580 for (String key : restrictions.keySet()) {
1581 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001582 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001583 serializer.attribute(null, ATTR_KEY, key);
1584
1585 if (value instanceof Boolean) {
1586 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1587 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001588 } else if (value instanceof Integer) {
1589 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1590 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001591 } else if (value == null || value instanceof String) {
1592 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1593 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001594 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001595 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1596 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001597 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001598 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001599 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001600 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001601 serializer.endTag(null, TAG_VALUE);
1602 }
1603 }
1604 serializer.endTag(null, TAG_ENTRY);
1605 }
1606
1607 serializer.endTag(null, TAG_RESTRICTIONS);
1608
1609 serializer.endDocument();
1610 restrictionsFile.finishWrite(fos);
1611 } catch (Exception e) {
1612 restrictionsFile.failWrite(fos);
1613 Slog.e(LOG_TAG, "Error writing application restrictions list");
1614 }
1615 }
1616
1617 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001618 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001619 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001620 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001621 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001622 }
1623 }
1624
1625 @Override
1626 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001627 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001628 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001629 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001630 }
1631 // Not found
1632 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001633 }
1634 }
1635
Amith Yamasani0b285492011-04-14 17:35:23 -07001636 /**
1637 * Caches the list of user ids in an array, adjusting the array size when necessary.
1638 */
Amith Yamasani13593602012-03-22 16:16:17 -07001639 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001640 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001641 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001642 if (!mUsers.valueAt(i).partial) {
1643 num++;
1644 }
1645 }
Amith Yamasani16389312012-10-17 21:20:14 -07001646 final int[] newUsers = new int[num];
1647 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001648 for (int i = 0; i < mUsers.size(); i++) {
1649 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001650 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001651 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001652 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001653 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001654 }
1655
1656 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001657 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001658 * @param userId the user that was just foregrounded
1659 */
1660 public void userForeground(int userId) {
1661 synchronized (mPackagesLock) {
1662 UserInfo user = mUsers.get(userId);
1663 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001664 if (user == null || user.partial) {
1665 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1666 return;
1667 }
1668 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001669 user.lastLoggedInTime = now;
1670 writeUserLocked(user);
1671 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001672 // If this is not a restricted profile and there is no restrictions pin, clean up
1673 // all restrictions files that might have been left behind, else clean up just the
1674 // ones with uninstalled packages
1675 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1676 final long salt = pinState == null ? 0 : pinState.salt;
1677 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001678 }
1679 }
1680
1681 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001682 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001683 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1684 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001685 * @return
1686 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001687 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001688 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001689 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001690 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001691 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001692 break;
1693 }
1694 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001695 }
Amith Yamasani195263742012-08-21 15:40:12 -07001696 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001697 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001698 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001699
Amith Yamasanifc95e702013-09-26 13:20:17 -07001700 private String packageToRestrictionsFileName(String packageName) {
1701 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1702 }
1703
1704 private String restrictionsFileNameToPackage(String fileName) {
1705 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1706 (int) (fileName.length() - XML_SUFFIX.length()));
1707 }
1708
Amith Yamasani920ace02012-09-20 22:15:37 -07001709 @Override
1710 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1711 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1712 != PackageManager.PERMISSION_GRANTED) {
1713 pw.println("Permission Denial: can't dump UserManager from from pid="
1714 + Binder.getCallingPid()
1715 + ", uid=" + Binder.getCallingUid()
1716 + " without permission "
1717 + android.Manifest.permission.DUMP);
1718 return;
1719 }
1720
1721 long now = System.currentTimeMillis();
1722 StringBuilder sb = new StringBuilder();
1723 synchronized (mPackagesLock) {
1724 pw.println("Users:");
1725 for (int i = 0; i < mUsers.size(); i++) {
1726 UserInfo user = mUsers.valueAt(i);
1727 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001728 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001729 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001730 if (user.partial) pw.print(" <partial>");
1731 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001732 pw.print(" Created: ");
1733 if (user.creationTime == 0) {
1734 pw.println("<unknown>");
1735 } else {
1736 sb.setLength(0);
1737 TimeUtils.formatDuration(now - user.creationTime, sb);
1738 sb.append(" ago");
1739 pw.println(sb);
1740 }
1741 pw.print(" Last logged in: ");
1742 if (user.lastLoggedInTime == 0) {
1743 pw.println("<unknown>");
1744 } else {
1745 sb.setLength(0);
1746 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1747 sb.append(" ago");
1748 pw.println(sb);
1749 }
1750 }
1751 }
1752 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001753
1754 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1755 @Override
1756 public void onPackageRemoved(String pkg, int uid) {
1757 final int userId = this.getChangingUserId();
1758 // Package could be disappearing because it is being blocked, so also check if
1759 // it has been uninstalled.
1760 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1761 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1762 cleanAppRestrictionsForPackage(pkg, userId);
1763 }
1764 }
1765 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001766}