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