UserManagerService.java revision 06bf824628c118fbd5ad6756913d7fd63a6f4ce5
1/* 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 19import android.app.Activity; 20import android.app.ActivityManager; 21import android.app.ActivityManagerNative; 22import android.app.IStopUserCallback; 23import android.content.BroadcastReceiver; 24import android.content.Context; 25import android.content.Intent; 26import android.content.pm.ApplicationInfo; 27import android.content.pm.PackageManager; 28import android.content.pm.PackageManager.NameNotFoundException; 29import android.content.pm.UserInfo; 30import android.graphics.Bitmap; 31import android.os.Binder; 32import android.os.Bundle; 33import android.os.Environment; 34import android.os.FileUtils; 35import android.os.Handler; 36import android.os.IUserManager; 37import android.os.Message; 38import android.os.ParcelFileDescriptor; 39import android.os.Parcelable; 40import android.os.Process; 41import android.os.RemoteException; 42import android.os.ServiceManager; 43import android.os.UserHandle; 44import android.os.UserManager; 45import android.util.AtomicFile; 46import android.util.Log; 47import android.util.Slog; 48import android.util.SparseArray; 49import android.util.SparseBooleanArray; 50import android.util.TimeUtils; 51import android.util.Xml; 52 53import com.google.android.collect.Sets; 54 55import com.android.internal.annotations.VisibleForTesting; 56import com.android.internal.app.IAppOpsService; 57import com.android.internal.util.ArrayUtils; 58import com.android.internal.util.FastXmlSerializer; 59import com.android.internal.util.XmlUtils; 60 61import org.xmlpull.v1.XmlPullParser; 62import org.xmlpull.v1.XmlPullParserException; 63import org.xmlpull.v1.XmlSerializer; 64 65import java.io.BufferedOutputStream; 66import java.io.File; 67import java.io.FileDescriptor; 68import java.io.FileInputStream; 69import java.io.FileNotFoundException; 70import java.io.FileOutputStream; 71import java.io.IOException; 72import java.io.PrintWriter; 73import java.util.ArrayList; 74import java.util.List; 75import java.util.Set; 76 77import libcore.io.IoUtils; 78 79public class UserManagerService extends IUserManager.Stub { 80 81 private static final String LOG_TAG = "UserManagerService"; 82 83 private static final boolean DBG = false; 84 85 private static final String TAG_NAME = "name"; 86 private static final String ATTR_FLAGS = "flags"; 87 private static final String ATTR_ICON_PATH = "icon"; 88 private static final String ATTR_ID = "id"; 89 private static final String ATTR_CREATION_TIME = "created"; 90 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn"; 91 private static final String ATTR_SERIAL_NO = "serialNumber"; 92 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber"; 93 private static final String ATTR_PARTIAL = "partial"; 94 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove"; 95 private static final String ATTR_USER_VERSION = "version"; 96 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId"; 97 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions"; 98 private static final String TAG_USERS = "users"; 99 private static final String TAG_USER = "user"; 100 private static final String TAG_RESTRICTIONS = "restrictions"; 101 private static final String TAG_ENTRY = "entry"; 102 private static final String TAG_VALUE = "value"; 103 private static final String ATTR_KEY = "key"; 104 private static final String ATTR_VALUE_TYPE = "type"; 105 private static final String ATTR_MULTIPLE = "m"; 106 107 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"; 110 private static final String ATTR_TYPE_INTEGER = "i"; 111 private static final String ATTR_TYPE_BUNDLE = "B"; 112 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA"; 113 114 private static final String USER_INFO_DIR = "system" + File.separator + "users"; 115 private static final String USER_LIST_FILENAME = "userlist.xml"; 116 private static final String USER_PHOTO_FILENAME = "photo.png"; 117 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp"; 118 119 private static final String RESTRICTIONS_FILE_PREFIX = "res_"; 120 private static final String XML_SUFFIX = ".xml"; 121 122 private static final int MIN_USER_ID = 10; 123 124 private static final int USER_VERSION = 5; 125 126 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms 127 128 // Maximum number of managed profiles permitted is 1. This cannot be increased 129 // without first making sure that the rest of the framework is prepared for it. 130 private static final int MAX_MANAGED_PROFILES = 1; 131 132 // Set of user restrictions, which can only be enforced by the system 133 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet( 134 UserManager.DISALLOW_RECORD_AUDIO); 135 136 static final int WRITE_USER_MSG = 1; 137 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds 138 139 private final Context mContext; 140 private final PackageManagerService mPm; 141 private final Object mInstallLock; 142 private final Object mPackagesLock; 143 144 private final Handler mHandler; 145 146 private final File mUsersDir; 147 private final File mUserListFile; 148 private final File mBaseUserPath; 149 150 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>(); 151 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>(); 152 private final Bundle mGuestRestrictions = new Bundle(); 153 154 /** 155 * Set of user IDs being actively removed. Removed IDs linger in this set 156 * for several seconds to work around a VFS caching issue. 157 */ 158 // @GuardedBy("mPackagesLock") 159 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray(); 160 161 private int[] mUserIds; 162 private int mNextSerialNumber; 163 private int mUserVersion = 0; 164 165 private IAppOpsService mAppOpsService; 166 167 private static UserManagerService sInstance; 168 169 public static UserManagerService getInstance() { 170 synchronized (UserManagerService.class) { 171 return sInstance; 172 } 173 } 174 175 /** 176 * Available for testing purposes. 177 */ 178 UserManagerService(File dataDir, File baseUserPath) { 179 this(null, null, new Object(), new Object(), dataDir, baseUserPath); 180 } 181 182 /** 183 * Called by package manager to create the service. This is closely 184 * associated with the package manager, and the given lock is the 185 * package manager's own lock. 186 */ 187 UserManagerService(Context context, PackageManagerService pm, 188 Object installLock, Object packagesLock) { 189 this(context, pm, installLock, packagesLock, 190 Environment.getDataDirectory(), 191 new File(Environment.getDataDirectory(), "user")); 192 } 193 194 /** 195 * Available for testing purposes. 196 */ 197 private UserManagerService(Context context, PackageManagerService pm, 198 Object installLock, Object packagesLock, 199 File dataDir, File baseUserPath) { 200 mContext = context; 201 mPm = pm; 202 mInstallLock = installLock; 203 mPackagesLock = packagesLock; 204 mHandler = new MainHandler(); 205 synchronized (mInstallLock) { 206 synchronized (mPackagesLock) { 207 mUsersDir = new File(dataDir, USER_INFO_DIR); 208 mUsersDir.mkdirs(); 209 // Make zeroth user directory, for services to migrate their files to that location 210 File userZeroDir = new File(mUsersDir, "0"); 211 userZeroDir.mkdirs(); 212 mBaseUserPath = baseUserPath; 213 FileUtils.setPermissions(mUsersDir.toString(), 214 FileUtils.S_IRWXU|FileUtils.S_IRWXG 215 |FileUtils.S_IROTH|FileUtils.S_IXOTH, 216 -1, -1); 217 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME); 218 initDefaultGuestRestrictions(); 219 readUserListLocked(); 220 sInstance = this; 221 } 222 } 223 } 224 225 void systemReady() { 226 synchronized (mInstallLock) { 227 synchronized (mPackagesLock) { 228 // Prune out any partially created/partially removed users. 229 ArrayList<UserInfo> partials = new ArrayList<UserInfo>(); 230 for (int i = 0; i < mUsers.size(); i++) { 231 UserInfo ui = mUsers.valueAt(i); 232 if ((ui.partial || ui.guestToRemove) && i != 0) { 233 partials.add(ui); 234 } 235 } 236 for (int i = 0; i < partials.size(); i++) { 237 UserInfo ui = partials.get(i); 238 Slog.w(LOG_TAG, "Removing partially created user #" + i 239 + " (name=" + ui.name + ")"); 240 removeUserStateLocked(ui.id); 241 } 242 } 243 } 244 onUserForeground(UserHandle.USER_OWNER); 245 mAppOpsService = IAppOpsService.Stub.asInterface( 246 ServiceManager.getService(Context.APP_OPS_SERVICE)); 247 for (int i = 0; i < mUserIds.length; ++i) { 248 try { 249 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]); 250 } catch (RemoteException e) { 251 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions"); 252 } 253 } 254 } 255 256 @Override 257 public List<UserInfo> getUsers(boolean excludeDying) { 258 checkManageUsersPermission("query users"); 259 synchronized (mPackagesLock) { 260 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size()); 261 for (int i = 0; i < mUsers.size(); i++) { 262 UserInfo ui = mUsers.valueAt(i); 263 if (ui.partial) { 264 continue; 265 } 266 if (!excludeDying || !mRemovingUserIds.get(ui.id)) { 267 users.add(ui); 268 } 269 } 270 return users; 271 } 272 } 273 274 @Override 275 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) { 276 if (userId != UserHandle.getCallingUserId()) { 277 checkManageUsersPermission("getting profiles related to user " + userId); 278 } 279 final long ident = Binder.clearCallingIdentity(); 280 try { 281 synchronized (mPackagesLock) { 282 return getProfilesLocked(userId, enabledOnly); 283 } 284 } finally { 285 Binder.restoreCallingIdentity(ident); 286 } 287 } 288 289 /** Assume permissions already checked and caller's identity cleared */ 290 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) { 291 UserInfo user = getUserInfoLocked(userId); 292 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size()); 293 if (user == null) { 294 // Probably a dying user 295 return users; 296 } 297 for (int i = 0; i < mUsers.size(); i++) { 298 UserInfo profile = mUsers.valueAt(i); 299 if (!isProfileOf(user, profile)) { 300 continue; 301 } 302 if (enabledOnly && !profile.isEnabled()) { 303 continue; 304 } 305 if (mRemovingUserIds.get(profile.id)) { 306 continue; 307 } 308 users.add(profile); 309 } 310 return users; 311 } 312 313 @Override 314 public UserInfo getProfileParent(int userHandle) { 315 checkManageUsersPermission("get the profile parent"); 316 synchronized (mPackagesLock) { 317 return getProfileParentLocked(userHandle); 318 } 319 } 320 321 private UserInfo getProfileParentLocked(int userHandle) { 322 UserInfo profile = getUserInfoLocked(userHandle); 323 if (profile == null) { 324 return null; 325 } 326 int parentUserId = profile.profileGroupId; 327 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) { 328 return null; 329 } else { 330 return getUserInfoLocked(parentUserId); 331 } 332 } 333 334 private boolean isProfileOf(UserInfo user, UserInfo profile) { 335 return user.id == profile.id || 336 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID 337 && user.profileGroupId == profile.profileGroupId); 338 } 339 340 @Override 341 public void setUserEnabled(int userId) { 342 checkManageUsersPermission("enable user"); 343 synchronized (mPackagesLock) { 344 UserInfo info = getUserInfoLocked(userId); 345 if (info != null && !info.isEnabled()) { 346 info.flags ^= UserInfo.FLAG_DISABLED; 347 writeUserLocked(info); 348 } 349 } 350 } 351 352 @Override 353 public UserInfo getUserInfo(int userId) { 354 checkManageUsersPermission("query user"); 355 synchronized (mPackagesLock) { 356 return getUserInfoLocked(userId); 357 } 358 } 359 360 @Override 361 public boolean isRestricted() { 362 synchronized (mPackagesLock) { 363 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted(); 364 } 365 } 366 367 /* 368 * Should be locked on mUsers before calling this. 369 */ 370 private UserInfo getUserInfoLocked(int userId) { 371 UserInfo ui = mUsers.get(userId); 372 // If it is partial and not in the process of being removed, return as unknown user. 373 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) { 374 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId); 375 return null; 376 } 377 return ui; 378 } 379 380 public boolean exists(int userId) { 381 synchronized (mPackagesLock) { 382 return ArrayUtils.contains(mUserIds, userId); 383 } 384 } 385 386 @Override 387 public void setUserName(int userId, String name) { 388 checkManageUsersPermission("rename users"); 389 boolean changed = false; 390 synchronized (mPackagesLock) { 391 UserInfo info = mUsers.get(userId); 392 if (info == null || info.partial) { 393 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId); 394 return; 395 } 396 if (name != null && !name.equals(info.name)) { 397 info.name = name; 398 writeUserLocked(info); 399 changed = true; 400 } 401 } 402 if (changed) { 403 sendUserInfoChangedBroadcast(userId); 404 } 405 } 406 407 @Override 408 public void setUserIcon(int userId, Bitmap bitmap) { 409 checkManageUsersPermission("update users"); 410 long ident = Binder.clearCallingIdentity(); 411 try { 412 synchronized (mPackagesLock) { 413 UserInfo info = mUsers.get(userId); 414 if (info == null || info.partial) { 415 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId); 416 return; 417 } 418 writeBitmapLocked(info, bitmap); 419 writeUserLocked(info); 420 } 421 sendUserInfoChangedBroadcast(userId); 422 } finally { 423 Binder.restoreCallingIdentity(ident); 424 } 425 } 426 427 private void sendUserInfoChangedBroadcast(int userId) { 428 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED); 429 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 430 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 431 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL); 432 } 433 434 @Override 435 public ParcelFileDescriptor getUserIcon(int userId) { 436 String iconPath; 437 synchronized (mPackagesLock) { 438 UserInfo info = mUsers.get(userId); 439 if (info == null || info.partial) { 440 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId); 441 return null; 442 } 443 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId; 444 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID 445 || callingGroupId != info.profileGroupId) { 446 checkManageUsersPermission("get the icon of a user who is not related"); 447 } 448 if (info.iconPath == null) { 449 return null; 450 } 451 iconPath = info.iconPath; 452 } 453 454 try { 455 return ParcelFileDescriptor.open( 456 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY); 457 } catch (FileNotFoundException e) { 458 Log.e(LOG_TAG, "Couldn't find icon file", e); 459 } 460 return null; 461 } 462 463 public void makeInitialized(int userId) { 464 checkManageUsersPermission("makeInitialized"); 465 synchronized (mPackagesLock) { 466 UserInfo info = mUsers.get(userId); 467 if (info == null || info.partial) { 468 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId); 469 } 470 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) { 471 info.flags |= UserInfo.FLAG_INITIALIZED; 472 scheduleWriteUserLocked(info); 473 } 474 } 475 } 476 477 /** 478 * If default guest restrictions haven't been initialized yet, add the basic 479 * restrictions. 480 */ 481 private void initDefaultGuestRestrictions() { 482 if (mGuestRestrictions.isEmpty()) { 483 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true); 484 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true); 485 } 486 } 487 488 @Override 489 public Bundle getDefaultGuestRestrictions() { 490 checkManageUsersPermission("getDefaultGuestRestrictions"); 491 synchronized (mPackagesLock) { 492 return new Bundle(mGuestRestrictions); 493 } 494 } 495 496 @Override 497 public void setDefaultGuestRestrictions(Bundle restrictions) { 498 checkManageUsersPermission("setDefaultGuestRestrictions"); 499 synchronized (mPackagesLock) { 500 mGuestRestrictions.clear(); 501 mGuestRestrictions.putAll(restrictions); 502 writeUserListLocked(); 503 } 504 } 505 506 @Override 507 public boolean hasUserRestriction(String restrictionKey, int userId) { 508 synchronized (mPackagesLock) { 509 Bundle restrictions = mUserRestrictions.get(userId); 510 return restrictions != null && restrictions.getBoolean(restrictionKey); 511 } 512 } 513 514 @Override 515 public Bundle getUserRestrictions(int userId) { 516 // checkManageUsersPermission("getUserRestrictions"); 517 518 synchronized (mPackagesLock) { 519 Bundle restrictions = mUserRestrictions.get(userId); 520 return restrictions != null ? new Bundle(restrictions) : new Bundle(); 521 } 522 } 523 524 @Override 525 public void setUserRestriction(String key, boolean value, int userId) { 526 synchronized (mPackagesLock) { 527 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) { 528 Bundle restrictions = getUserRestrictions(userId); 529 restrictions.putBoolean(key, value); 530 setUserRestrictionsInternalLocked(restrictions, userId); 531 } 532 } 533 } 534 535 @Override 536 public void setSystemControlledUserRestriction(String key, boolean value, int userId) { 537 checkSystemOrRoot("setSystemControlledUserRestriction"); 538 synchronized (mPackagesLock) { 539 Bundle restrictions = getUserRestrictions(userId); 540 restrictions.putBoolean(key, value); 541 setUserRestrictionsInternalLocked(restrictions, userId); 542 } 543 } 544 545 @Override 546 public void setUserRestrictions(Bundle restrictions, int userId) { 547 checkManageUsersPermission("setUserRestrictions"); 548 if (restrictions == null) return; 549 550 synchronized (mPackagesLock) { 551 final Bundle oldUserRestrictions = mUserRestrictions.get(userId); 552 // Restore the original state of system controlled restrictions from oldUserRestrictions 553 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) { 554 restrictions.remove(key); 555 if (oldUserRestrictions.containsKey(key)) { 556 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key)); 557 } 558 } 559 setUserRestrictionsInternalLocked(restrictions, userId); 560 } 561 } 562 563 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) { 564 final Bundle userRestrictions = mUserRestrictions.get(userId); 565 userRestrictions.clear(); 566 userRestrictions.putAll(restrictions); 567 long token = Binder.clearCallingIdentity(); 568 try { 569 mAppOpsService.setUserRestrictions(userRestrictions, userId); 570 } catch (RemoteException e) { 571 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions"); 572 } finally { 573 Binder.restoreCallingIdentity(token); 574 } 575 scheduleWriteUserLocked(mUsers.get(userId)); 576 } 577 578 /** 579 * Check if we've hit the limit of how many users can be created. 580 */ 581 private boolean isUserLimitReachedLocked() { 582 int aliveUserCount = 0; 583 final int totalUserCount = mUsers.size(); 584 // Skip over users being removed 585 for (int i = 0; i < totalUserCount; i++) { 586 UserInfo user = mUsers.valueAt(i); 587 if (!mRemovingUserIds.get(user.id) 588 && !user.isGuest() && !user.partial) { 589 aliveUserCount++; 590 } 591 } 592 return aliveUserCount >= UserManager.getMaxSupportedUsers(); 593 } 594 595 /** 596 * Enforces that only the system UID or root's UID or apps that have the 597 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} 598 * permission can make certain calls to the UserManager. 599 * 600 * @param message used as message if SecurityException is thrown 601 * @throws SecurityException if the caller is not system or root 602 */ 603 private static final void checkManageUsersPermission(String message) { 604 final int uid = Binder.getCallingUid(); 605 if (uid != Process.SYSTEM_UID && uid != 0 606 && ActivityManager.checkComponentPermission( 607 android.Manifest.permission.MANAGE_USERS, 608 uid, -1, true) != PackageManager.PERMISSION_GRANTED) { 609 throw new SecurityException("You need MANAGE_USERS permission to: " + message); 610 } 611 } 612 613 private static void checkSystemOrRoot(String message) { 614 final int uid = Binder.getCallingUid(); 615 if (uid != Process.SYSTEM_UID && uid != 0) { 616 throw new SecurityException("Only system may call: " + message); 617 } 618 } 619 620 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) { 621 try { 622 File dir = new File(mUsersDir, Integer.toString(info.id)); 623 File file = new File(dir, USER_PHOTO_FILENAME); 624 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP); 625 if (!dir.exists()) { 626 dir.mkdir(); 627 FileUtils.setPermissions( 628 dir.getPath(), 629 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 630 -1, -1); 631 } 632 FileOutputStream os; 633 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp)) 634 && tmp.renameTo(file)) { 635 info.iconPath = file.getAbsolutePath(); 636 } 637 try { 638 os.close(); 639 } catch (IOException ioe) { 640 // What the ... ! 641 } 642 tmp.delete(); 643 } catch (FileNotFoundException e) { 644 Slog.w(LOG_TAG, "Error setting photo for user ", e); 645 } 646 } 647 648 /** 649 * Returns an array of user ids. This array is cached here for quick access, so do not modify or 650 * cache it elsewhere. 651 * @return the array of user ids. 652 */ 653 public int[] getUserIds() { 654 synchronized (mPackagesLock) { 655 return mUserIds; 656 } 657 } 658 659 int[] getUserIdsLPr() { 660 return mUserIds; 661 } 662 663 private void readUserListLocked() { 664 if (!mUserListFile.exists()) { 665 fallbackToSingleUserLocked(); 666 return; 667 } 668 FileInputStream fis = null; 669 AtomicFile userListFile = new AtomicFile(mUserListFile); 670 try { 671 fis = userListFile.openRead(); 672 XmlPullParser parser = Xml.newPullParser(); 673 parser.setInput(fis, null); 674 int type; 675 while ((type = parser.next()) != XmlPullParser.START_TAG 676 && type != XmlPullParser.END_DOCUMENT) { 677 ; 678 } 679 680 if (type != XmlPullParser.START_TAG) { 681 Slog.e(LOG_TAG, "Unable to read user list"); 682 fallbackToSingleUserLocked(); 683 return; 684 } 685 686 mNextSerialNumber = -1; 687 if (parser.getName().equals(TAG_USERS)) { 688 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO); 689 if (lastSerialNumber != null) { 690 mNextSerialNumber = Integer.parseInt(lastSerialNumber); 691 } 692 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION); 693 if (versionNumber != null) { 694 mUserVersion = Integer.parseInt(versionNumber); 695 } 696 } 697 698 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 699 if (type == XmlPullParser.START_TAG) { 700 final String name = parser.getName(); 701 if (name.equals(TAG_USER)) { 702 String id = parser.getAttributeValue(null, ATTR_ID); 703 UserInfo user = readUserLocked(Integer.parseInt(id)); 704 705 if (user != null) { 706 mUsers.put(user.id, user); 707 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) { 708 mNextSerialNumber = user.id + 1; 709 } 710 } 711 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) { 712 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 713 && type != XmlPullParser.END_TAG) { 714 if (type == XmlPullParser.START_TAG) { 715 if (parser.getName().equals(TAG_RESTRICTIONS)) { 716 readRestrictionsLocked(parser, mGuestRestrictions); 717 } 718 break; 719 } 720 } 721 } 722 } 723 } 724 updateUserIdsLocked(); 725 upgradeIfNecessaryLocked(); 726 } catch (IOException ioe) { 727 fallbackToSingleUserLocked(); 728 } catch (XmlPullParserException pe) { 729 fallbackToSingleUserLocked(); 730 } finally { 731 if (fis != null) { 732 try { 733 fis.close(); 734 } catch (IOException e) { 735 } 736 } 737 } 738 } 739 740 /** 741 * Upgrade steps between versions, either for fixing bugs or changing the data format. 742 */ 743 private void upgradeIfNecessaryLocked() { 744 int userVersion = mUserVersion; 745 if (userVersion < 1) { 746 // Assign a proper name for the owner, if not initialized correctly before 747 UserInfo user = mUsers.get(UserHandle.USER_OWNER); 748 if ("Primary".equals(user.name)) { 749 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name); 750 scheduleWriteUserLocked(user); 751 } 752 userVersion = 1; 753 } 754 755 if (userVersion < 2) { 756 // Owner should be marked as initialized 757 UserInfo user = mUsers.get(UserHandle.USER_OWNER); 758 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) { 759 user.flags |= UserInfo.FLAG_INITIALIZED; 760 scheduleWriteUserLocked(user); 761 } 762 userVersion = 2; 763 } 764 765 766 if (userVersion < 4) { 767 userVersion = 4; 768 } 769 770 if (userVersion < 5) { 771 initDefaultGuestRestrictions(); 772 userVersion = 5; 773 } 774 775 if (userVersion < USER_VERSION) { 776 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to " 777 + USER_VERSION); 778 } else { 779 mUserVersion = userVersion; 780 writeUserListLocked(); 781 } 782 } 783 784 private void fallbackToSingleUserLocked() { 785 // Create the primary user 786 UserInfo primary = new UserInfo(UserHandle.USER_OWNER, 787 mContext.getResources().getString(com.android.internal.R.string.owner_name), null, 788 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED); 789 mUsers.put(0, primary); 790 mNextSerialNumber = MIN_USER_ID; 791 mUserVersion = USER_VERSION; 792 793 Bundle restrictions = new Bundle(); 794 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions); 795 796 updateUserIdsLocked(); 797 initDefaultGuestRestrictions(); 798 799 writeUserListLocked(); 800 writeUserLocked(primary); 801 } 802 803 private void scheduleWriteUserLocked(UserInfo userInfo) { 804 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) { 805 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo); 806 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY); 807 } 808 } 809 810 /* 811 * Writes the user file in this format: 812 * 813 * <user flags="20039023" id="0"> 814 * <name>Primary</name> 815 * </user> 816 */ 817 private void writeUserLocked(UserInfo userInfo) { 818 FileOutputStream fos = null; 819 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX)); 820 try { 821 fos = userFile.startWrite(); 822 final BufferedOutputStream bos = new BufferedOutputStream(fos); 823 824 // XmlSerializer serializer = XmlUtils.serializerInstance(); 825 final XmlSerializer serializer = new FastXmlSerializer(); 826 serializer.setOutput(bos, "utf-8"); 827 serializer.startDocument(null, true); 828 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 829 830 serializer.startTag(null, TAG_USER); 831 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id)); 832 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber)); 833 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags)); 834 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime)); 835 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME, 836 Long.toString(userInfo.lastLoggedInTime)); 837 if (userInfo.iconPath != null) { 838 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath); 839 } 840 if (userInfo.partial) { 841 serializer.attribute(null, ATTR_PARTIAL, "true"); 842 } 843 if (userInfo.guestToRemove) { 844 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true"); 845 } 846 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) { 847 serializer.attribute(null, ATTR_PROFILE_GROUP_ID, 848 Integer.toString(userInfo.profileGroupId)); 849 } 850 851 serializer.startTag(null, TAG_NAME); 852 serializer.text(userInfo.name); 853 serializer.endTag(null, TAG_NAME); 854 Bundle restrictions = mUserRestrictions.get(userInfo.id); 855 if (restrictions != null) { 856 writeRestrictionsLocked(serializer, restrictions); 857 } 858 serializer.endTag(null, TAG_USER); 859 860 serializer.endDocument(); 861 userFile.finishWrite(fos); 862 } catch (Exception ioe) { 863 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe); 864 userFile.failWrite(fos); 865 } 866 } 867 868 /* 869 * Writes the user list file in this format: 870 * 871 * <users nextSerialNumber="3"> 872 * <user id="0"></user> 873 * <user id="2"></user> 874 * </users> 875 */ 876 private void writeUserListLocked() { 877 FileOutputStream fos = null; 878 AtomicFile userListFile = new AtomicFile(mUserListFile); 879 try { 880 fos = userListFile.startWrite(); 881 final BufferedOutputStream bos = new BufferedOutputStream(fos); 882 883 // XmlSerializer serializer = XmlUtils.serializerInstance(); 884 final XmlSerializer serializer = new FastXmlSerializer(); 885 serializer.setOutput(bos, "utf-8"); 886 serializer.startDocument(null, true); 887 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 888 889 serializer.startTag(null, TAG_USERS); 890 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber)); 891 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion)); 892 893 serializer.startTag(null, TAG_GUEST_RESTRICTIONS); 894 writeRestrictionsLocked(serializer, mGuestRestrictions); 895 serializer.endTag(null, TAG_GUEST_RESTRICTIONS); 896 for (int i = 0; i < mUsers.size(); i++) { 897 UserInfo user = mUsers.valueAt(i); 898 serializer.startTag(null, TAG_USER); 899 serializer.attribute(null, ATTR_ID, Integer.toString(user.id)); 900 serializer.endTag(null, TAG_USER); 901 } 902 903 serializer.endTag(null, TAG_USERS); 904 905 serializer.endDocument(); 906 userListFile.finishWrite(fos); 907 } catch (Exception e) { 908 userListFile.failWrite(fos); 909 Slog.e(LOG_TAG, "Error writing user list"); 910 } 911 } 912 913 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions) 914 throws IOException { 915 serializer.startTag(null, TAG_RESTRICTIONS); 916 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI); 917 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS); 918 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS); 919 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS); 920 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION); 921 writeBoolean(serializer, restrictions, 922 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 923 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH); 924 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER); 925 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS); 926 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER); 927 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES); 928 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN); 929 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING); 930 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET); 931 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER); 932 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS); 933 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS); 934 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS); 935 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL); 936 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA); 937 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE); 938 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME); 939 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS); 940 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS); 941 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS); 942 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE); 943 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM); 944 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER); 945 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT); 946 serializer.endTag(null, TAG_RESTRICTIONS); 947 } 948 949 private UserInfo readUserLocked(int id) { 950 int flags = 0; 951 int serialNumber = id; 952 String name = null; 953 String iconPath = null; 954 long creationTime = 0L; 955 long lastLoggedInTime = 0L; 956 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID; 957 boolean partial = false; 958 boolean guestToRemove = false; 959 Bundle restrictions = new Bundle(); 960 961 FileInputStream fis = null; 962 try { 963 AtomicFile userFile = 964 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX)); 965 fis = userFile.openRead(); 966 XmlPullParser parser = Xml.newPullParser(); 967 parser.setInput(fis, null); 968 int type; 969 while ((type = parser.next()) != XmlPullParser.START_TAG 970 && type != XmlPullParser.END_DOCUMENT) { 971 ; 972 } 973 974 if (type != XmlPullParser.START_TAG) { 975 Slog.e(LOG_TAG, "Unable to read user " + id); 976 return null; 977 } 978 979 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) { 980 int storedId = readIntAttribute(parser, ATTR_ID, -1); 981 if (storedId != id) { 982 Slog.e(LOG_TAG, "User id does not match the file name"); 983 return null; 984 } 985 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id); 986 flags = readIntAttribute(parser, ATTR_FLAGS, 0); 987 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH); 988 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0); 989 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0); 990 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID, 991 UserInfo.NO_PROFILE_GROUP_ID); 992 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL); 993 if ("true".equals(valueString)) { 994 partial = true; 995 } 996 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE); 997 if ("true".equals(valueString)) { 998 guestToRemove = true; 999 } 1000 1001 int outerDepth = parser.getDepth(); 1002 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 1003 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 1004 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 1005 continue; 1006 } 1007 String tag = parser.getName(); 1008 if (TAG_NAME.equals(tag)) { 1009 type = parser.next(); 1010 if (type == XmlPullParser.TEXT) { 1011 name = parser.getText(); 1012 } 1013 } else if (TAG_RESTRICTIONS.equals(tag)) { 1014 readRestrictionsLocked(parser, restrictions); 1015 } 1016 } 1017 } 1018 1019 UserInfo userInfo = new UserInfo(id, name, iconPath, flags); 1020 userInfo.serialNumber = serialNumber; 1021 userInfo.creationTime = creationTime; 1022 userInfo.lastLoggedInTime = lastLoggedInTime; 1023 userInfo.partial = partial; 1024 userInfo.guestToRemove = guestToRemove; 1025 userInfo.profileGroupId = profileGroupId; 1026 mUserRestrictions.append(id, restrictions); 1027 return userInfo; 1028 1029 } catch (IOException ioe) { 1030 } catch (XmlPullParserException pe) { 1031 } finally { 1032 if (fis != null) { 1033 try { 1034 fis.close(); 1035 } catch (IOException e) { 1036 } 1037 } 1038 } 1039 return null; 1040 } 1041 1042 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions) 1043 throws IOException { 1044 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI); 1045 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS); 1046 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS); 1047 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS); 1048 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION); 1049 readBoolean(parser, restrictions, 1050 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 1051 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH); 1052 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER); 1053 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS); 1054 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER); 1055 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES); 1056 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN); 1057 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING); 1058 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET); 1059 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER); 1060 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS); 1061 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS); 1062 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS); 1063 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL); 1064 readBoolean(parser, restrictions, 1065 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA); 1066 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1067 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME); 1068 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS); 1069 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS); 1070 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS); 1071 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE); 1072 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM); 1073 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER); 1074 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT); 1075 } 1076 1077 private void readBoolean(XmlPullParser parser, Bundle restrictions, 1078 String restrictionKey) { 1079 String value = parser.getAttributeValue(null, restrictionKey); 1080 if (value != null) { 1081 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value)); 1082 } 1083 } 1084 1085 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey) 1086 throws IOException { 1087 if (restrictions.containsKey(restrictionKey)) { 1088 xml.attribute(null, restrictionKey, 1089 Boolean.toString(restrictions.getBoolean(restrictionKey))); 1090 } 1091 } 1092 1093 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) { 1094 String valueString = parser.getAttributeValue(null, attr); 1095 if (valueString == null) return defaultValue; 1096 try { 1097 return Integer.parseInt(valueString); 1098 } catch (NumberFormatException nfe) { 1099 return defaultValue; 1100 } 1101 } 1102 1103 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) { 1104 String valueString = parser.getAttributeValue(null, attr); 1105 if (valueString == null) return defaultValue; 1106 try { 1107 return Long.parseLong(valueString); 1108 } catch (NumberFormatException nfe) { 1109 return defaultValue; 1110 } 1111 } 1112 1113 private boolean isPackageInstalled(String pkg, int userId) { 1114 final ApplicationInfo info = mPm.getApplicationInfo(pkg, 1115 PackageManager.GET_UNINSTALLED_PACKAGES, 1116 userId); 1117 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) { 1118 return false; 1119 } 1120 return true; 1121 } 1122 1123 /** 1124 * Removes all the restrictions files (res_<packagename>) for a given user. 1125 * Does not do any permissions checking. 1126 */ 1127 private void cleanAppRestrictions(int userId) { 1128 synchronized (mPackagesLock) { 1129 File dir = Environment.getUserSystemDirectory(userId); 1130 String[] files = dir.list(); 1131 if (files == null) return; 1132 for (String fileName : files) { 1133 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) { 1134 File resFile = new File(dir, fileName); 1135 if (resFile.exists()) { 1136 resFile.delete(); 1137 } 1138 } 1139 } 1140 } 1141 } 1142 1143 /** 1144 * Removes the app restrictions file for a specific package and user id, if it exists. 1145 */ 1146 private void cleanAppRestrictionsForPackage(String pkg, int userId) { 1147 synchronized (mPackagesLock) { 1148 File dir = Environment.getUserSystemDirectory(userId); 1149 File resFile = new File(dir, packageToRestrictionsFileName(pkg)); 1150 if (resFile.exists()) { 1151 resFile.delete(); 1152 } 1153 } 1154 } 1155 1156 @Override 1157 public UserInfo createProfileForUser(String name, int flags, int userId) { 1158 checkManageUsersPermission("Only the system can create users"); 1159 if (userId != UserHandle.USER_OWNER) { 1160 Slog.w(LOG_TAG, "Only user owner can have profiles"); 1161 return null; 1162 } 1163 return createUserInternal(name, flags, userId); 1164 } 1165 1166 @Override 1167 public UserInfo createUser(String name, int flags) { 1168 checkManageUsersPermission("Only the system can create users"); 1169 return createUserInternal(name, flags, UserHandle.USER_NULL); 1170 } 1171 1172 private UserInfo createUserInternal(String name, int flags, int parentId) { 1173 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean( 1174 UserManager.DISALLOW_ADD_USER, false)) { 1175 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled."); 1176 return null; 1177 } 1178 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0; 1179 final long ident = Binder.clearCallingIdentity(); 1180 UserInfo userInfo = null; 1181 try { 1182 synchronized (mInstallLock) { 1183 synchronized (mPackagesLock) { 1184 UserInfo parent = null; 1185 if (parentId != UserHandle.USER_NULL) { 1186 parent = getUserInfoLocked(parentId); 1187 if (parent == null) return null; 1188 } 1189 // If we're not adding a guest user and the limit has been reached, 1190 // cannot add a user. 1191 if (!isGuest && isUserLimitReachedLocked()) { 1192 return null; 1193 } 1194 // If we're adding a guest and there already exists one, bail. 1195 if (isGuest && findCurrentGuestUserLocked() != null) { 1196 return null; 1197 } 1198 // Limit number of managed profiles that can be created 1199 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0 1200 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true) 1201 >= MAX_MANAGED_PROFILES) { 1202 return null; 1203 } 1204 int userId = getNextAvailableIdLocked(); 1205 userInfo = new UserInfo(userId, name, null, flags); 1206 File userPath = new File(mBaseUserPath, Integer.toString(userId)); 1207 userInfo.serialNumber = mNextSerialNumber++; 1208 long now = System.currentTimeMillis(); 1209 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0; 1210 userInfo.partial = true; 1211 Environment.getUserSystemDirectory(userInfo.id).mkdirs(); 1212 mUsers.put(userId, userInfo); 1213 writeUserListLocked(); 1214 if (parent != null) { 1215 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) { 1216 parent.profileGroupId = parent.id; 1217 scheduleWriteUserLocked(parent); 1218 } 1219 userInfo.profileGroupId = parent.profileGroupId; 1220 } 1221 mPm.createNewUserLILPw(userId, userPath); 1222 userInfo.partial = false; 1223 scheduleWriteUserLocked(userInfo); 1224 updateUserIdsLocked(); 1225 Bundle restrictions = new Bundle(); 1226 mUserRestrictions.append(userId, restrictions); 1227 mPm.newUserCreatedLILPw(userId); 1228 } 1229 } 1230 if (userInfo != null) { 1231 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED); 1232 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id); 1233 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL, 1234 android.Manifest.permission.MANAGE_USERS); 1235 } 1236 } finally { 1237 Binder.restoreCallingIdentity(ident); 1238 } 1239 return userInfo; 1240 } 1241 1242 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) { 1243 int count = 0; 1244 for (int i = mUsers.size() - 1; i >= 0; i--) { 1245 UserInfo user = mUsers.valueAt(i); 1246 if (!excludeDying || !mRemovingUserIds.get(user.id)) { 1247 if ((user.flags & flags) != 0) { 1248 count++; 1249 } 1250 } 1251 } 1252 return count; 1253 } 1254 1255 /** 1256 * Find the current guest user. If the Guest user is partial, 1257 * then do not include it in the results as it is about to die. 1258 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to 1259 * the special handling of Guests being removed. 1260 */ 1261 private UserInfo findCurrentGuestUserLocked() { 1262 final int size = mUsers.size(); 1263 for (int i = 0; i < size; i++) { 1264 final UserInfo user = mUsers.valueAt(i); 1265 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) { 1266 return user; 1267 } 1268 } 1269 return null; 1270 } 1271 1272 /** 1273 * Mark this guest user for deletion to allow us to create another guest 1274 * and switch to that user before actually removing this guest. 1275 * @param userHandle the userid of the current guest 1276 * @return whether the user could be marked for deletion 1277 */ 1278 public boolean markGuestForDeletion(int userHandle) { 1279 checkManageUsersPermission("Only the system can remove users"); 1280 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean( 1281 UserManager.DISALLOW_REMOVE_USER, false)) { 1282 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled."); 1283 return false; 1284 } 1285 1286 long ident = Binder.clearCallingIdentity(); 1287 try { 1288 final UserInfo user; 1289 synchronized (mPackagesLock) { 1290 user = mUsers.get(userHandle); 1291 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) { 1292 return false; 1293 } 1294 if (!user.isGuest()) { 1295 return false; 1296 } 1297 // We set this to a guest user that is to be removed. This is a temporary state 1298 // where we are allowed to add new Guest users, even if this one is still not 1299 // removed. This user will still show up in getUserInfo() calls. 1300 // If we don't get around to removing this Guest user, it will be purged on next 1301 // startup. 1302 user.guestToRemove = true; 1303 // Mark it as disabled, so that it isn't returned any more when 1304 // profiles are queried. 1305 user.flags |= UserInfo.FLAG_DISABLED; 1306 writeUserLocked(user); 1307 } 1308 } finally { 1309 Binder.restoreCallingIdentity(ident); 1310 } 1311 return true; 1312 } 1313 1314 /** 1315 * Removes a user and all data directories created for that user. This method should be called 1316 * after the user's processes have been terminated. 1317 * @param userHandle the user's id 1318 */ 1319 public boolean removeUser(int userHandle) { 1320 checkManageUsersPermission("Only the system can remove users"); 1321 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean( 1322 UserManager.DISALLOW_REMOVE_USER, false)) { 1323 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled."); 1324 return false; 1325 } 1326 1327 long ident = Binder.clearCallingIdentity(); 1328 try { 1329 final UserInfo user; 1330 synchronized (mPackagesLock) { 1331 user = mUsers.get(userHandle); 1332 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) { 1333 return false; 1334 } 1335 1336 // We remember deleted user IDs to prevent them from being 1337 // reused during the current boot; they can still be reused 1338 // after a reboot. 1339 mRemovingUserIds.put(userHandle, true); 1340 1341 try { 1342 mAppOpsService.removeUser(userHandle); 1343 } catch (RemoteException e) { 1344 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e); 1345 } 1346 // Set this to a partially created user, so that the user will be purged 1347 // on next startup, in case the runtime stops now before stopping and 1348 // removing the user completely. 1349 user.partial = true; 1350 // Mark it as disabled, so that it isn't returned any more when 1351 // profiles are queried. 1352 user.flags |= UserInfo.FLAG_DISABLED; 1353 writeUserLocked(user); 1354 } 1355 1356 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID 1357 && user.isManagedProfile()) { 1358 // Send broadcast to notify system that the user removed was a 1359 // managed user. 1360 sendProfileRemovedBroadcast(user.profileGroupId, user.id); 1361 } 1362 1363 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle); 1364 int res; 1365 try { 1366 res = ActivityManagerNative.getDefault().stopUser(userHandle, 1367 new IStopUserCallback.Stub() { 1368 @Override 1369 public void userStopped(int userId) { 1370 finishRemoveUser(userId); 1371 } 1372 @Override 1373 public void userStopAborted(int userId) { 1374 } 1375 }); 1376 } catch (RemoteException e) { 1377 return false; 1378 } 1379 return res == ActivityManager.USER_OP_SUCCESS; 1380 } finally { 1381 Binder.restoreCallingIdentity(ident); 1382 } 1383 } 1384 1385 void finishRemoveUser(final int userHandle) { 1386 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle); 1387 // Let other services shutdown any activity and clean up their state before completely 1388 // wiping the user's system directory and removing from the user list 1389 long ident = Binder.clearCallingIdentity(); 1390 try { 1391 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED); 1392 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle); 1393 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL, 1394 android.Manifest.permission.MANAGE_USERS, 1395 1396 new BroadcastReceiver() { 1397 @Override 1398 public void onReceive(Context context, Intent intent) { 1399 if (DBG) { 1400 Slog.i(LOG_TAG, 1401 "USER_REMOVED broadcast sent, cleaning up user data " 1402 + userHandle); 1403 } 1404 new Thread() { 1405 public void run() { 1406 synchronized (mInstallLock) { 1407 synchronized (mPackagesLock) { 1408 removeUserStateLocked(userHandle); 1409 } 1410 } 1411 } 1412 }.start(); 1413 } 1414 }, 1415 1416 null, Activity.RESULT_OK, null, null); 1417 } finally { 1418 Binder.restoreCallingIdentity(ident); 1419 } 1420 } 1421 1422 private void removeUserStateLocked(final int userHandle) { 1423 // Cleanup package manager settings 1424 mPm.cleanUpUserLILPw(this, userHandle); 1425 1426 // Remove this user from the list 1427 mUsers.remove(userHandle); 1428 // Remove user file 1429 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX)); 1430 userFile.delete(); 1431 // Update the user list 1432 writeUserListLocked(); 1433 updateUserIdsLocked(); 1434 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle)); 1435 } 1436 1437 private void removeDirectoryRecursive(File parent) { 1438 if (parent.isDirectory()) { 1439 String[] files = parent.list(); 1440 for (String filename : files) { 1441 File child = new File(parent, filename); 1442 removeDirectoryRecursive(child); 1443 } 1444 } 1445 parent.delete(); 1446 } 1447 1448 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) { 1449 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED); 1450 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 1451 Intent.FLAG_RECEIVER_FOREGROUND); 1452 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId)); 1453 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null); 1454 } 1455 1456 @Override 1457 public Bundle getApplicationRestrictions(String packageName) { 1458 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId()); 1459 } 1460 1461 @Override 1462 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) { 1463 if (UserHandle.getCallingUserId() != userId 1464 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) { 1465 checkManageUsersPermission("Only system can get restrictions for other users/apps"); 1466 } 1467 synchronized (mPackagesLock) { 1468 // Read the restrictions from XML 1469 return readApplicationRestrictionsLocked(packageName, userId); 1470 } 1471 } 1472 1473 @Override 1474 public void setApplicationRestrictions(String packageName, Bundle restrictions, 1475 int userId) { 1476 if (UserHandle.getCallingUserId() != userId 1477 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) { 1478 checkManageUsersPermission("Only system can set restrictions for other users/apps"); 1479 } 1480 synchronized (mPackagesLock) { 1481 if (restrictions == null || restrictions.isEmpty()) { 1482 cleanAppRestrictionsForPackage(packageName, userId); 1483 } else { 1484 // Write the restrictions to XML 1485 writeApplicationRestrictionsLocked(packageName, restrictions, userId); 1486 } 1487 } 1488 1489 if (isPackageInstalled(packageName, userId)) { 1490 // Notify package of changes via an intent - only sent to explicitly registered receivers. 1491 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED); 1492 changeIntent.setPackage(packageName); 1493 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 1494 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId)); 1495 } 1496 } 1497 1498 @Override 1499 public void removeRestrictions() { 1500 checkManageUsersPermission("Only system can remove restrictions"); 1501 final int userHandle = UserHandle.getCallingUserId(); 1502 removeRestrictionsForUser(userHandle, true); 1503 } 1504 1505 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) { 1506 synchronized (mPackagesLock) { 1507 // Remove all user restrictions 1508 setUserRestrictions(new Bundle(), userHandle); 1509 // Remove any app restrictions 1510 cleanAppRestrictions(userHandle); 1511 } 1512 if (unhideApps) { 1513 unhideAllInstalledAppsForUser(userHandle); 1514 } 1515 } 1516 1517 private void unhideAllInstalledAppsForUser(final int userHandle) { 1518 mHandler.post(new Runnable() { 1519 @Override 1520 public void run() { 1521 List<ApplicationInfo> apps = 1522 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES, 1523 userHandle).getList(); 1524 final long ident = Binder.clearCallingIdentity(); 1525 try { 1526 for (ApplicationInfo appInfo : apps) { 1527 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0 1528 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN) 1529 != 0) { 1530 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false, 1531 userHandle); 1532 } 1533 } 1534 } finally { 1535 Binder.restoreCallingIdentity(ident); 1536 } 1537 } 1538 }); 1539 } 1540 private int getUidForPackage(String packageName) { 1541 long ident = Binder.clearCallingIdentity(); 1542 try { 1543 return mContext.getPackageManager().getApplicationInfo(packageName, 1544 PackageManager.GET_UNINSTALLED_PACKAGES).uid; 1545 } catch (NameNotFoundException nnfe) { 1546 return -1; 1547 } finally { 1548 Binder.restoreCallingIdentity(ident); 1549 } 1550 } 1551 1552 private Bundle readApplicationRestrictionsLocked(String packageName, 1553 int userId) { 1554 AtomicFile restrictionsFile = 1555 new AtomicFile(new File(Environment.getUserSystemDirectory(userId), 1556 packageToRestrictionsFileName(packageName))); 1557 return readApplicationRestrictionsLocked(restrictionsFile); 1558 } 1559 1560 @VisibleForTesting 1561 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) { 1562 final Bundle restrictions = new Bundle(); 1563 final ArrayList<String> values = new ArrayList<>(); 1564 if (!restrictionsFile.getBaseFile().exists()) { 1565 return restrictions; 1566 } 1567 1568 FileInputStream fis = null; 1569 try { 1570 fis = restrictionsFile.openRead(); 1571 XmlPullParser parser = Xml.newPullParser(); 1572 parser.setInput(fis, null); 1573 XmlUtils.nextElement(parser); 1574 if (parser.getEventType() != XmlPullParser.START_TAG) { 1575 Slog.e(LOG_TAG, "Unable to read restrictions file " 1576 + restrictionsFile.getBaseFile()); 1577 return restrictions; 1578 } 1579 while (parser.next() != XmlPullParser.END_DOCUMENT) { 1580 readEntry(restrictions, values, parser); 1581 } 1582 } catch (IOException|XmlPullParserException e) { 1583 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e); 1584 } finally { 1585 IoUtils.closeQuietly(fis); 1586 } 1587 return restrictions; 1588 } 1589 1590 private static void readEntry(Bundle restrictions, ArrayList<String> values, 1591 XmlPullParser parser) throws XmlPullParserException, IOException { 1592 int type = parser.getEventType(); 1593 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) { 1594 String key = parser.getAttributeValue(null, ATTR_KEY); 1595 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE); 1596 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE); 1597 if (multiple != null) { 1598 values.clear(); 1599 int count = Integer.parseInt(multiple); 1600 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) { 1601 if (type == XmlPullParser.START_TAG 1602 && parser.getName().equals(TAG_VALUE)) { 1603 values.add(parser.nextText().trim()); 1604 count--; 1605 } 1606 } 1607 String [] valueStrings = new String[values.size()]; 1608 values.toArray(valueStrings); 1609 restrictions.putStringArray(key, valueStrings); 1610 } else if (ATTR_TYPE_BUNDLE.equals(valType)) { 1611 restrictions.putBundle(key, readBundleEntry(parser, values)); 1612 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) { 1613 final int outerDepth = parser.getDepth(); 1614 ArrayList<Bundle> bundleList = new ArrayList<>(); 1615 while (XmlUtils.nextElementWithin(parser, outerDepth)) { 1616 Bundle childBundle = readBundleEntry(parser, values); 1617 bundleList.add(childBundle); 1618 } 1619 restrictions.putParcelableArray(key, 1620 bundleList.toArray(new Bundle[bundleList.size()])); 1621 } else { 1622 String value = parser.nextText().trim(); 1623 if (ATTR_TYPE_BOOLEAN.equals(valType)) { 1624 restrictions.putBoolean(key, Boolean.parseBoolean(value)); 1625 } else if (ATTR_TYPE_INTEGER.equals(valType)) { 1626 restrictions.putInt(key, Integer.parseInt(value)); 1627 } else { 1628 restrictions.putString(key, value); 1629 } 1630 } 1631 } 1632 } 1633 1634 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values) 1635 throws IOException, XmlPullParserException { 1636 Bundle childBundle = new Bundle(); 1637 final int outerDepth = parser.getDepth(); 1638 while (XmlUtils.nextElementWithin(parser, outerDepth)) { 1639 readEntry(childBundle, values, parser); 1640 } 1641 return childBundle; 1642 } 1643 1644 private void writeApplicationRestrictionsLocked(String packageName, 1645 Bundle restrictions, int userId) { 1646 AtomicFile restrictionsFile = new AtomicFile( 1647 new File(Environment.getUserSystemDirectory(userId), 1648 packageToRestrictionsFileName(packageName))); 1649 writeApplicationRestrictionsLocked(restrictions, restrictionsFile); 1650 } 1651 1652 @VisibleForTesting 1653 static void writeApplicationRestrictionsLocked(Bundle restrictions, 1654 AtomicFile restrictionsFile) { 1655 FileOutputStream fos = null; 1656 try { 1657 fos = restrictionsFile.startWrite(); 1658 final BufferedOutputStream bos = new BufferedOutputStream(fos); 1659 1660 final XmlSerializer serializer = new FastXmlSerializer(); 1661 serializer.setOutput(bos, "utf-8"); 1662 serializer.startDocument(null, true); 1663 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 1664 1665 serializer.startTag(null, TAG_RESTRICTIONS); 1666 writeBundle(restrictions, serializer); 1667 serializer.endTag(null, TAG_RESTRICTIONS); 1668 1669 serializer.endDocument(); 1670 restrictionsFile.finishWrite(fos); 1671 } catch (Exception e) { 1672 restrictionsFile.failWrite(fos); 1673 Slog.e(LOG_TAG, "Error writing application restrictions list", e); 1674 } 1675 } 1676 1677 private static void writeBundle(Bundle restrictions, XmlSerializer serializer) 1678 throws IOException { 1679 for (String key : restrictions.keySet()) { 1680 Object value = restrictions.get(key); 1681 serializer.startTag(null, TAG_ENTRY); 1682 serializer.attribute(null, ATTR_KEY, key); 1683 1684 if (value instanceof Boolean) { 1685 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN); 1686 serializer.text(value.toString()); 1687 } else if (value instanceof Integer) { 1688 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER); 1689 serializer.text(value.toString()); 1690 } else if (value == null || value instanceof String) { 1691 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING); 1692 serializer.text(value != null ? (String) value : ""); 1693 } else if (value instanceof Bundle) { 1694 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE); 1695 writeBundle((Bundle) value, serializer); 1696 } else if (value instanceof Parcelable[]) { 1697 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY); 1698 Parcelable[] array = (Parcelable[]) value; 1699 for (Parcelable parcelable : array) { 1700 if (!(parcelable instanceof Bundle)) { 1701 throw new IllegalArgumentException("bundle-array can only hold Bundles"); 1702 } 1703 serializer.startTag(null, TAG_ENTRY); 1704 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE); 1705 writeBundle((Bundle) parcelable, serializer); 1706 serializer.endTag(null, TAG_ENTRY); 1707 } 1708 } else { 1709 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY); 1710 String[] values = (String[]) value; 1711 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length)); 1712 for (String choice : values) { 1713 serializer.startTag(null, TAG_VALUE); 1714 serializer.text(choice != null ? choice : ""); 1715 serializer.endTag(null, TAG_VALUE); 1716 } 1717 } 1718 serializer.endTag(null, TAG_ENTRY); 1719 } 1720 } 1721 1722 @Override 1723 public int getUserSerialNumber(int userHandle) { 1724 synchronized (mPackagesLock) { 1725 if (!exists(userHandle)) return -1; 1726 return getUserInfoLocked(userHandle).serialNumber; 1727 } 1728 } 1729 1730 @Override 1731 public int getUserHandle(int userSerialNumber) { 1732 synchronized (mPackagesLock) { 1733 for (int userId : mUserIds) { 1734 UserInfo info = getUserInfoLocked(userId); 1735 if (info != null && info.serialNumber == userSerialNumber) return userId; 1736 } 1737 // Not found 1738 return -1; 1739 } 1740 } 1741 1742 @Override 1743 public long getUserCreationTime(int userHandle) { 1744 int callingUserId = UserHandle.getCallingUserId(); 1745 UserInfo userInfo = null; 1746 synchronized (mPackagesLock) { 1747 if (callingUserId == userHandle) { 1748 userInfo = getUserInfoLocked(userHandle); 1749 } else { 1750 UserInfo parent = getProfileParentLocked(userHandle); 1751 if (parent != null && parent.id == callingUserId) { 1752 userInfo = getUserInfoLocked(userHandle); 1753 } 1754 } 1755 } 1756 if (userInfo == null) { 1757 throw new SecurityException("userHandle can only be the calling user or a managed " 1758 + "profile associated with this user"); 1759 } 1760 return userInfo.creationTime; 1761 } 1762 1763 /** 1764 * Caches the list of user ids in an array, adjusting the array size when necessary. 1765 */ 1766 private void updateUserIdsLocked() { 1767 int num = 0; 1768 for (int i = 0; i < mUsers.size(); i++) { 1769 if (!mUsers.valueAt(i).partial) { 1770 num++; 1771 } 1772 } 1773 final int[] newUsers = new int[num]; 1774 int n = 0; 1775 for (int i = 0; i < mUsers.size(); i++) { 1776 if (!mUsers.valueAt(i).partial) { 1777 newUsers[n++] = mUsers.keyAt(i); 1778 } 1779 } 1780 mUserIds = newUsers; 1781 } 1782 1783 /** 1784 * Make a note of the last started time of a user and do some cleanup. 1785 * @param userId the user that was just foregrounded 1786 */ 1787 public void onUserForeground(int userId) { 1788 synchronized (mPackagesLock) { 1789 UserInfo user = mUsers.get(userId); 1790 long now = System.currentTimeMillis(); 1791 if (user == null || user.partial) { 1792 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId); 1793 return; 1794 } 1795 if (now > EPOCH_PLUS_30_YEARS) { 1796 user.lastLoggedInTime = now; 1797 scheduleWriteUserLocked(user); 1798 } 1799 } 1800 } 1801 1802 /** 1803 * Returns the next available user id, filling in any holes in the ids. 1804 * TODO: May not be a good idea to recycle ids, in case it results in confusion 1805 * for data and battery stats collection, or unexpected cross-talk. 1806 * @return 1807 */ 1808 private int getNextAvailableIdLocked() { 1809 synchronized (mPackagesLock) { 1810 int i = MIN_USER_ID; 1811 while (i < Integer.MAX_VALUE) { 1812 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) { 1813 break; 1814 } 1815 i++; 1816 } 1817 return i; 1818 } 1819 } 1820 1821 private String packageToRestrictionsFileName(String packageName) { 1822 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX; 1823 } 1824 1825 @Override 1826 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1827 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 1828 != PackageManager.PERMISSION_GRANTED) { 1829 pw.println("Permission Denial: can't dump UserManager from from pid=" 1830 + Binder.getCallingPid() 1831 + ", uid=" + Binder.getCallingUid() 1832 + " without permission " 1833 + android.Manifest.permission.DUMP); 1834 return; 1835 } 1836 1837 long now = System.currentTimeMillis(); 1838 StringBuilder sb = new StringBuilder(); 1839 synchronized (mPackagesLock) { 1840 pw.println("Users:"); 1841 for (int i = 0; i < mUsers.size(); i++) { 1842 UserInfo user = mUsers.valueAt(i); 1843 if (user == null) continue; 1844 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber); 1845 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> "); 1846 if (user.partial) pw.print(" <partial>"); 1847 pw.println(); 1848 pw.print(" Created: "); 1849 if (user.creationTime == 0) { 1850 pw.println("<unknown>"); 1851 } else { 1852 sb.setLength(0); 1853 TimeUtils.formatDuration(now - user.creationTime, sb); 1854 sb.append(" ago"); 1855 pw.println(sb); 1856 } 1857 pw.print(" Last logged in: "); 1858 if (user.lastLoggedInTime == 0) { 1859 pw.println("<unknown>"); 1860 } else { 1861 sb.setLength(0); 1862 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb); 1863 sb.append(" ago"); 1864 pw.println(sb); 1865 } 1866 } 1867 } 1868 } 1869 1870 final class MainHandler extends Handler { 1871 1872 @Override 1873 public void handleMessage(Message msg) { 1874 switch (msg.what) { 1875 case WRITE_USER_MSG: 1876 removeMessages(WRITE_USER_MSG, msg.obj); 1877 synchronized (mPackagesLock) { 1878 int userId = ((UserInfo) msg.obj).id; 1879 UserInfo userInfo = mUsers.get(userId); 1880 if (userInfo != null) { 1881 writeUserLocked(userInfo); 1882 } 1883 } 1884 } 1885 } 1886 } 1887} 1888