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