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