Home | History | Annotate | Download | only in devicepolicy
      1 /*
      2  * Copyright (C) 2010 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 
     17 package com.android.server.devicepolicy;
     18 
     19 import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
     20 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
     21 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
     22 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
     23 import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
     24 
     25 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
     26 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
     27 import static org.xmlpull.v1.XmlPullParser.END_TAG;
     28 import static org.xmlpull.v1.XmlPullParser.TEXT;
     29 
     30 import android.Manifest.permission;
     31 import android.accessibilityservice.AccessibilityServiceInfo;
     32 import android.accounts.Account;
     33 import android.accounts.AccountManager;
     34 import android.annotation.IntDef;
     35 import android.annotation.NonNull;
     36 import android.annotation.Nullable;
     37 import android.annotation.UserIdInt;
     38 import android.app.Activity;
     39 import android.app.ActivityManager;
     40 import android.app.ActivityManagerNative;
     41 import android.app.AlarmManager;
     42 import android.app.AppGlobals;
     43 import android.app.IActivityManager;
     44 import android.app.Notification;
     45 import android.app.NotificationManager;
     46 import android.app.PendingIntent;
     47 import android.app.StatusBarManager;
     48 import android.app.admin.DeviceAdminInfo;
     49 import android.app.admin.DeviceAdminReceiver;
     50 import android.app.admin.DevicePolicyManager;
     51 import android.app.admin.DevicePolicyManagerInternal;
     52 import android.app.admin.IDevicePolicyManager;
     53 import android.app.admin.SecurityLog;
     54 import android.app.admin.SecurityLog.SecurityEvent;
     55 import android.app.admin.SystemUpdatePolicy;
     56 import android.app.backup.IBackupManager;
     57 import android.app.trust.TrustManager;
     58 import android.content.BroadcastReceiver;
     59 import android.content.ComponentName;
     60 import android.content.Context;
     61 import android.content.Intent;
     62 import android.content.IntentFilter;
     63 import android.content.pm.ActivityInfo;
     64 import android.content.pm.ApplicationInfo;
     65 import android.content.pm.IPackageManager;
     66 import android.content.pm.PackageInfo;
     67 import android.content.pm.PackageManager;
     68 import android.content.pm.PackageManager.NameNotFoundException;
     69 import android.content.pm.PackageManagerInternal;
     70 import android.content.pm.ParceledListSlice;
     71 import android.content.pm.ResolveInfo;
     72 import android.content.pm.ServiceInfo;
     73 import android.content.pm.UserInfo;
     74 import android.database.ContentObserver;
     75 import android.graphics.Bitmap;
     76 import android.graphics.Color;
     77 import android.media.AudioManager;
     78 import android.media.IAudioService;
     79 import android.net.ConnectivityManager;
     80 import android.net.ProxyInfo;
     81 import android.net.Uri;
     82 import android.net.wifi.WifiInfo;
     83 import android.net.wifi.WifiManager;
     84 import android.os.AsyncTask;
     85 import android.os.Binder;
     86 import android.os.Build;
     87 import android.os.Bundle;
     88 import android.os.Environment;
     89 import android.os.FileUtils;
     90 import android.os.Handler;
     91 import android.os.IBinder;
     92 import android.os.Looper;
     93 import android.os.ParcelFileDescriptor;
     94 import android.os.PersistableBundle;
     95 import android.os.PowerManager;
     96 import android.os.PowerManagerInternal;
     97 import android.os.Process;
     98 import android.os.RecoverySystem;
     99 import android.os.RemoteCallback;
    100 import android.os.RemoteException;
    101 import android.os.ServiceManager;
    102 import android.os.SystemClock;
    103 import android.os.SystemProperties;
    104 import android.os.UserHandle;
    105 import android.os.UserManager;
    106 import android.os.UserManagerInternal;
    107 import android.os.storage.StorageManager;
    108 import android.provider.ContactsContract.QuickContact;
    109 import android.provider.ContactsInternal;
    110 import android.provider.Settings;
    111 import android.security.Credentials;
    112 import android.security.IKeyChainAliasCallback;
    113 import android.security.IKeyChainService;
    114 import android.security.KeyChain;
    115 import android.security.KeyChain.KeyChainConnection;
    116 import android.service.persistentdata.PersistentDataBlockManager;
    117 import android.telephony.TelephonyManager;
    118 import android.text.TextUtils;
    119 import android.util.ArrayMap;
    120 import android.util.ArraySet;
    121 import android.util.Log;
    122 import android.util.Pair;
    123 import android.util.Slog;
    124 import android.util.SparseArray;
    125 import android.util.Xml;
    126 import android.view.IWindowManager;
    127 import android.view.accessibility.AccessibilityManager;
    128 import android.view.accessibility.IAccessibilityManager;
    129 import android.view.inputmethod.InputMethodInfo;
    130 import android.view.inputmethod.InputMethodManager;
    131 
    132 import com.android.internal.R;
    133 import com.android.internal.annotations.VisibleForTesting;
    134 import com.android.internal.statusbar.IStatusBarService;
    135 import com.android.internal.util.FastXmlSerializer;
    136 import com.android.internal.util.JournaledFile;
    137 import com.android.internal.util.ParcelableString;
    138 import com.android.internal.util.Preconditions;
    139 import com.android.internal.util.XmlUtils;
    140 import com.android.internal.widget.LockPatternUtils;
    141 import com.android.server.LocalServices;
    142 import com.android.server.SystemService;
    143 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
    144 import com.android.server.pm.UserRestrictionsUtils;
    145 import com.google.android.collect.Sets;
    146 
    147 import org.xmlpull.v1.XmlPullParser;
    148 import org.xmlpull.v1.XmlPullParserException;
    149 import org.xmlpull.v1.XmlSerializer;
    150 
    151 import java.io.ByteArrayInputStream;
    152 import java.io.File;
    153 import java.io.FileDescriptor;
    154 import java.io.FileInputStream;
    155 import java.io.FileNotFoundException;
    156 import java.io.FileOutputStream;
    157 import java.io.IOException;
    158 import java.io.PrintWriter;
    159 import java.lang.annotation.Retention;
    160 import java.lang.annotation.RetentionPolicy;
    161 import java.nio.charset.StandardCharsets;
    162 import java.security.cert.CertificateException;
    163 import java.security.cert.CertificateFactory;
    164 import java.security.cert.X509Certificate;
    165 import java.text.DateFormat;
    166 import java.util.ArrayList;
    167 import java.util.Arrays;
    168 import java.util.Collections;
    169 import java.util.Date;
    170 import java.util.List;
    171 import java.util.Map.Entry;
    172 import java.util.Set;
    173 import java.util.concurrent.atomic.AtomicBoolean;
    174 
    175 /**
    176  * Implementation of the device policy APIs.
    177  */
    178 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
    179 
    180     private static final String LOG_TAG = "DevicePolicyManagerService";
    181 
    182     private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
    183 
    184     private static final String DEVICE_POLICIES_XML = "device_policies.xml";
    185 
    186     private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
    187 
    188     private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
    189 
    190     private static final String TAG_STATUS_BAR = "statusbar";
    191 
    192     private static final String ATTR_DISABLED = "disabled";
    193 
    194     private static final String ATTR_NAME = "name";
    195 
    196     private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
    197             "do-not-ask-credentials-on-boot";
    198 
    199     private static final String TAG_AFFILIATION_ID = "affiliation-id";
    200 
    201     private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
    202 
    203     private static final String ATTR_VALUE = "value";
    204 
    205     private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
    206 
    207     private static final int REQUEST_EXPIRE_PASSWORD = 5571;
    208 
    209     private static final long MS_PER_DAY = 86400 * 1000;
    210 
    211     private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
    212 
    213     private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
    214             = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
    215 
    216     private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
    217     private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
    218 
    219     private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
    220     private static final String ATTR_SETUP_COMPLETE = "setup-complete";
    221     private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
    222     private static final String ATTR_PERMISSION_POLICY = "permission-policy";
    223     private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
    224             "device-provisioning-config-applied";
    225 
    226     private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
    227     private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
    228             = "application-restrictions-manager";
    229 
    230     /**
    231      *  System property whose value is either "true" or "false", indicating whether
    232      */
    233     private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
    234 
    235     private static final int STATUS_BAR_DISABLE_MASK =
    236             StatusBarManager.DISABLE_EXPAND |
    237             StatusBarManager.DISABLE_NOTIFICATION_ICONS |
    238             StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
    239             StatusBarManager.DISABLE_SEARCH;
    240 
    241     private static final int STATUS_BAR_DISABLE2_MASK =
    242             StatusBarManager.DISABLE2_QUICK_SETTINGS;
    243 
    244     private static final Set<String> SECURE_SETTINGS_WHITELIST;
    245     private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
    246     private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
    247     private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
    248     static {
    249         SECURE_SETTINGS_WHITELIST = new ArraySet<>();
    250         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
    251         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
    252         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
    253 
    254         SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
    255         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
    256         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
    257 
    258         GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
    259         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
    260         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
    261         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
    262         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
    263         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
    264         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
    265         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
    266         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
    267 
    268         GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
    269         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
    270         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
    271         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
    272         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
    273         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
    274     }
    275 
    276     /**
    277      * Keyguard features that when set on a managed profile that doesn't have its own challenge will
    278      * affect the profile's parent user. These can also be set on the managed profile's parent DPM
    279      * instance.
    280      */
    281     private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
    282             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
    283             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
    284 
    285     /**
    286      * Keyguard features that when set on a profile affect the profile content or challenge only.
    287      * These cannot be set on the managed profile's parent DPM instance
    288      */
    289     private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
    290             DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
    291 
    292     /** Keyguard features that are allowed to be set on a managed profile */
    293     private static final int PROFILE_KEYGUARD_FEATURES =
    294             PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
    295 
    296     private static final int CODE_OK = 0;
    297     private static final int CODE_HAS_DEVICE_OWNER = 1;
    298     private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
    299     private static final int CODE_USER_NOT_RUNNING = 3;
    300     private static final int CODE_USER_SETUP_COMPLETED = 4;
    301     private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
    302     private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
    303     private static final int CODE_NOT_SYSTEM_USER = 7;
    304 
    305     @Retention(RetentionPolicy.SOURCE)
    306     @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
    307             CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
    308     private @interface DeviceOwnerPreConditionCode {}
    309 
    310     private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
    311 
    312     /**
    313      * Minimum timeout in milliseconds after which unlocking with weak auth times out,
    314      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
    315      */
    316     private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
    317 
    318     final Context mContext;
    319     final Injector mInjector;
    320     final IPackageManager mIPackageManager;
    321     final UserManager mUserManager;
    322     final UserManagerInternal mUserManagerInternal;
    323     final TelephonyManager mTelephonyManager;
    324     private final LockPatternUtils mLockPatternUtils;
    325 
    326     /**
    327      * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
    328      * is requested for user u.
    329      */
    330     private final Set<Pair<String, Integer>> mPackagesToRemove =
    331             new ArraySet<Pair<String, Integer>>();
    332 
    333     final LocalService mLocalService;
    334 
    335     // Stores and loads state on device and profile owners.
    336     @VisibleForTesting
    337     final Owners mOwners;
    338 
    339     private final Binder mToken = new Binder();
    340 
    341     /**
    342      * Whether or not device admin feature is supported. If it isn't return defaults for all
    343      * public methods.
    344      */
    345     boolean mHasFeature;
    346 
    347     private final SecurityLogMonitor mSecurityLogMonitor;
    348 
    349     private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
    350     private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
    351 
    352     private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
    353         @Override
    354         public void run() {
    355             if(mRemoteBugreportServiceIsActive.get()) {
    356                 onBugreportFailed();
    357             }
    358         }
    359     };
    360 
    361     private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
    362 
    363         @Override
    364         public void onReceive(Context context, Intent intent) {
    365             if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
    366                     && mRemoteBugreportServiceIsActive.get()) {
    367                 onBugreportFinished(intent);
    368             }
    369         }
    370     };
    371 
    372     private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
    373 
    374         @Override
    375         public void onReceive(Context context, Intent intent) {
    376             String action = intent.getAction();
    377             mInjector.getNotificationManager().cancel(LOG_TAG,
    378                     RemoteBugreportUtils.NOTIFICATION_ID);
    379             if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
    380                 onBugreportSharingAccepted();
    381             } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
    382                 onBugreportSharingDeclined();
    383             }
    384             mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
    385         }
    386     };
    387 
    388     public static final class Lifecycle extends SystemService {
    389         private DevicePolicyManagerService mService;
    390 
    391         public Lifecycle(Context context) {
    392             super(context);
    393             mService = new DevicePolicyManagerService(context);
    394         }
    395 
    396         @Override
    397         public void onStart() {
    398             publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
    399         }
    400 
    401         @Override
    402         public void onBootPhase(int phase) {
    403             mService.systemReady(phase);
    404         }
    405 
    406         @Override
    407         public void onStartUser(int userHandle) {
    408             mService.onStartUser(userHandle);
    409         }
    410     }
    411 
    412     public static class DevicePolicyData {
    413         int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
    414         int mActivePasswordLength = 0;
    415         int mActivePasswordUpperCase = 0;
    416         int mActivePasswordLowerCase = 0;
    417         int mActivePasswordLetters = 0;
    418         int mActivePasswordNumeric = 0;
    419         int mActivePasswordSymbols = 0;
    420         int mActivePasswordNonLetter = 0;
    421         int mFailedPasswordAttempts = 0;
    422 
    423         int mUserHandle;
    424         int mPasswordOwner = -1;
    425         long mLastMaximumTimeToLock = -1;
    426         boolean mUserSetupComplete = false;
    427         int mUserProvisioningState;
    428         int mPermissionPolicy;
    429 
    430         boolean mDeviceProvisioningConfigApplied = false;
    431 
    432         final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
    433         final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
    434         final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
    435 
    436         final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
    437 
    438         // This is the list of component allowed to start lock task mode.
    439         List<String> mLockTaskPackages = new ArrayList<>();
    440 
    441         boolean mStatusBarDisabled = false;
    442 
    443         ComponentName mRestrictionsProvider;
    444 
    445         String mDelegatedCertInstallerPackage;
    446 
    447         boolean doNotAskCredentialsOnBoot = false;
    448 
    449         String mApplicationRestrictionsManagingPackage;
    450 
    451         Set<String> mAffiliationIds = new ArraySet<>();
    452 
    453         // Used for initialization of users created by createAndManageUsers.
    454         boolean mAdminBroadcastPending = false;
    455         PersistableBundle mInitBundle = null;
    456 
    457         public DevicePolicyData(int userHandle) {
    458             mUserHandle = userHandle;
    459         }
    460     }
    461 
    462     final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
    463 
    464     final Handler mHandler;
    465 
    466     BroadcastReceiver mReceiver = new BroadcastReceiver() {
    467         @Override
    468         public void onReceive(Context context, Intent intent) {
    469             final String action = intent.getAction();
    470             final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
    471                     getSendingUserId());
    472 
    473             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
    474                     && userHandle == mOwners.getDeviceOwnerUserId()
    475                     && getDeviceOwnerRemoteBugreportUri() != null) {
    476                 IntentFilter filterConsent = new IntentFilter();
    477                 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
    478                 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
    479                 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
    480                 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
    481                         RemoteBugreportUtils.NOTIFICATION_ID,
    482                         RemoteBugreportUtils.buildNotification(mContext,
    483                                 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
    484                                 UserHandle.ALL);
    485             }
    486             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
    487                     || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
    488                 if (VERBOSE_LOG) {
    489                     Slog.v(LOG_TAG, "Sending password expiration notifications for action "
    490                             + action + " for user " + userHandle);
    491                 }
    492                 mHandler.post(new Runnable() {
    493                     @Override
    494                     public void run() {
    495                         handlePasswordExpirationNotification(userHandle);
    496                     }
    497                 });
    498             }
    499             if (Intent.ACTION_USER_UNLOCKED.equals(action)
    500                     || Intent.ACTION_USER_STARTED.equals(action)
    501                     || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
    502                 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
    503                 new MonitoringCertNotificationTask().execute(userId);
    504             }
    505             if (Intent.ACTION_USER_ADDED.equals(action)) {
    506                 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
    507             } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
    508                 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
    509                 removeUserData(userHandle);
    510             } else if (Intent.ACTION_USER_STARTED.equals(action)) {
    511                 synchronized (DevicePolicyManagerService.this) {
    512                     // Reset the policy data
    513                     mUserData.remove(userHandle);
    514                     sendAdminEnabledBroadcastLocked(userHandle);
    515                 }
    516                 handlePackagesChanged(null /* check all admins */, userHandle);
    517             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
    518                 handlePackagesChanged(null /* check all admins */, userHandle);
    519             } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
    520                     || (Intent.ACTION_PACKAGE_ADDED.equals(action)
    521                             && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
    522                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
    523             } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
    524                     && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
    525                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
    526             } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
    527                 clearWipeProfileNotification();
    528             }
    529         }
    530     };
    531 
    532     static class ActiveAdmin {
    533         private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
    534         private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
    535         private static final String TAG_DISABLE_CAMERA = "disable-camera";
    536         private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
    537         private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
    538         private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
    539                 = "disable-bt-contacts-sharing";
    540         private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
    541         private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
    542         private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
    543         private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
    544         private static final String TAG_ACCOUNT_TYPE = "account-type";
    545         private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
    546                 = "permitted-accessiblity-services";
    547         private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
    548         private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
    549         private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
    550         private static final String TAG_TRUST_AGENT_COMPONENT = "component";
    551         private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
    552         private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
    553         private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
    554         private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
    555         private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
    556         private static final String TAG_PERMITTED_IMES = "permitted-imes";
    557         private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
    558         private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
    559         private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
    560         private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
    561         private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
    562         private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
    563         private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
    564         private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
    565         private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
    566         private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
    567         private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
    568         private static final String ATTR_VALUE = "value";
    569         private static final String TAG_PASSWORD_QUALITY = "password-quality";
    570         private static final String TAG_POLICIES = "policies";
    571         private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
    572                 "cross-profile-widget-providers";
    573         private static final String TAG_PROVIDER = "provider";
    574         private static final String TAG_PACKAGE_LIST_ITEM  = "item";
    575         private static final String TAG_KEEP_UNINSTALLED_PACKAGES  = "keep-uninstalled-packages";
    576         private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
    577         private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
    578         private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
    579         private static final String TAG_PARENT_ADMIN = "parent-admin";
    580         private static final String TAG_ORGANIZATION_COLOR = "organization-color";
    581         private static final String TAG_ORGANIZATION_NAME = "organization-name";
    582 
    583         final DeviceAdminInfo info;
    584 
    585         int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
    586 
    587         static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
    588         int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
    589 
    590         static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
    591         int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
    592 
    593         static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
    594         int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
    595 
    596         static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
    597         int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
    598 
    599         static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
    600         int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
    601 
    602         static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
    603         int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
    604 
    605         static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
    606         int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
    607 
    608         static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
    609         int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
    610 
    611         static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
    612         long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
    613 
    614         long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
    615 
    616         static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
    617         int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
    618 
    619         static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
    620         long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
    621 
    622         static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
    623         long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
    624 
    625         static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
    626 
    627         int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
    628 
    629         boolean encryptionRequested = false;
    630         boolean testOnlyAdmin = false;
    631         boolean disableCamera = false;
    632         boolean disableCallerId = false;
    633         boolean disableContactsSearch = false;
    634         boolean disableBluetoothContactSharing = true;
    635         boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
    636         boolean requireAutoTime = false; // Can only be set by a device owner.
    637         boolean forceEphemeralUsers = false; // Can only be set by a device owner.
    638 
    639         ActiveAdmin parentAdmin;
    640         final boolean isParent;
    641 
    642         static class TrustAgentInfo {
    643             public PersistableBundle options;
    644             TrustAgentInfo(PersistableBundle bundle) {
    645                 options = bundle;
    646             }
    647         }
    648 
    649         Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
    650 
    651         // The list of permitted accessibility services package namesas set by a profile
    652         // or device owner. Null means all accessibility services are allowed, empty means
    653         // none except system services are allowed.
    654         List<String> permittedAccessiblityServices;
    655 
    656         // The list of permitted input methods package names as set by a profile or device owner.
    657         // Null means all input methods are allowed, empty means none except system imes are
    658         // allowed.
    659         List<String> permittedInputMethods;
    660 
    661         // List of package names to keep cached.
    662         List<String> keepUninstalledPackages;
    663 
    664         // TODO: review implementation decisions with frameworks team
    665         boolean specifiesGlobalProxy = false;
    666         String globalProxySpec = null;
    667         String globalProxyExclusionList = null;
    668 
    669         ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
    670 
    671         List<String> crossProfileWidgetProviders;
    672 
    673         Bundle userRestrictions;
    674 
    675         // Support text provided by the admin to display to the user.
    676         CharSequence shortSupportMessage = null;
    677         CharSequence longSupportMessage = null;
    678 
    679         // Background color of confirm credentials screen. Default: teal.
    680         static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
    681         int organizationColor = DEF_ORGANIZATION_COLOR;
    682 
    683         // Default title of confirm credentials screen
    684         String organizationName = null;
    685 
    686         ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
    687             info = _info;
    688             isParent = parent;
    689         }
    690 
    691         ActiveAdmin getParentActiveAdmin() {
    692             Preconditions.checkState(!isParent);
    693 
    694             if (parentAdmin == null) {
    695                 parentAdmin = new ActiveAdmin(info, /* parent */ true);
    696             }
    697             return parentAdmin;
    698         }
    699 
    700         boolean hasParentActiveAdmin() {
    701             return parentAdmin != null;
    702         }
    703 
    704         int getUid() { return info.getActivityInfo().applicationInfo.uid; }
    705 
    706         public UserHandle getUserHandle() {
    707             return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
    708         }
    709 
    710         void writeToXml(XmlSerializer out)
    711                 throws IllegalArgumentException, IllegalStateException, IOException {
    712             out.startTag(null, TAG_POLICIES);
    713             info.writePoliciesToXml(out);
    714             out.endTag(null, TAG_POLICIES);
    715             if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
    716                 out.startTag(null, TAG_PASSWORD_QUALITY);
    717                 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
    718                 out.endTag(null, TAG_PASSWORD_QUALITY);
    719                 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
    720                     out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
    721                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
    722                     out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
    723                 }
    724                 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
    725                     out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
    726                     out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
    727                     out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
    728                 }
    729                 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
    730                     out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
    731                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
    732                     out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
    733                 }
    734                 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
    735                     out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
    736                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
    737                     out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
    738                 }
    739                 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
    740                     out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
    741                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
    742                     out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
    743                 }
    744                 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
    745                     out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
    746                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
    747                     out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
    748                 }
    749                 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
    750                     out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
    751                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
    752                     out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
    753                 }
    754                 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
    755                     out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
    756                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
    757                     out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
    758                 }
    759             }
    760             if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
    761                 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
    762                 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
    763                 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
    764             }
    765             if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
    766                 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
    767                 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
    768                 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
    769             }
    770             if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
    771                 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
    772                 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
    773                 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
    774             }
    775             if (specifiesGlobalProxy) {
    776                 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
    777                 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
    778                 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
    779                 if (globalProxySpec != null) {
    780                     out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
    781                     out.attribute(null, ATTR_VALUE, globalProxySpec);
    782                     out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
    783                 }
    784                 if (globalProxyExclusionList != null) {
    785                     out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
    786                     out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
    787                     out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
    788                 }
    789             }
    790             if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
    791                 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
    792                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
    793                 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
    794             }
    795             if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
    796                 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
    797                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
    798                 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
    799             }
    800             if (encryptionRequested) {
    801                 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
    802                 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
    803                 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
    804             }
    805             if (testOnlyAdmin) {
    806                 out.startTag(null, TAG_TEST_ONLY_ADMIN);
    807                 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
    808                 out.endTag(null, TAG_TEST_ONLY_ADMIN);
    809             }
    810             if (disableCamera) {
    811                 out.startTag(null, TAG_DISABLE_CAMERA);
    812                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
    813                 out.endTag(null, TAG_DISABLE_CAMERA);
    814             }
    815             if (disableCallerId) {
    816                 out.startTag(null, TAG_DISABLE_CALLER_ID);
    817                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
    818                 out.endTag(null, TAG_DISABLE_CALLER_ID);
    819             }
    820             if (disableContactsSearch) {
    821                 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
    822                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
    823                 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
    824             }
    825             if (!disableBluetoothContactSharing) {
    826                 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
    827                 out.attribute(null, ATTR_VALUE,
    828                         Boolean.toString(disableBluetoothContactSharing));
    829                 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
    830             }
    831             if (disableScreenCapture) {
    832                 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
    833                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
    834                 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
    835             }
    836             if (requireAutoTime) {
    837                 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
    838                 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
    839                 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
    840             }
    841             if (forceEphemeralUsers) {
    842                 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
    843                 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
    844                 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
    845             }
    846             if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
    847                 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
    848                 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
    849                 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
    850             }
    851             if (!accountTypesWithManagementDisabled.isEmpty()) {
    852                 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
    853                 for (String ac : accountTypesWithManagementDisabled) {
    854                     out.startTag(null, TAG_ACCOUNT_TYPE);
    855                     out.attribute(null, ATTR_VALUE, ac);
    856                     out.endTag(null, TAG_ACCOUNT_TYPE);
    857                 }
    858                 out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
    859             }
    860             if (!trustAgentInfos.isEmpty()) {
    861                 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
    862                 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
    863                 for (Entry<String, TrustAgentInfo> entry : set) {
    864                     TrustAgentInfo trustAgentInfo = entry.getValue();
    865                     out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
    866                     out.attribute(null, ATTR_VALUE, entry.getKey());
    867                     if (trustAgentInfo.options != null) {
    868                         out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
    869                         try {
    870                             trustAgentInfo.options.saveToXml(out);
    871                         } catch (XmlPullParserException e) {
    872                             Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
    873                         }
    874                         out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
    875                     }
    876                     out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
    877                 }
    878                 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
    879             }
    880             if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
    881                 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
    882                 final int providerCount = crossProfileWidgetProviders.size();
    883                 for (int i = 0; i < providerCount; i++) {
    884                     String provider = crossProfileWidgetProviders.get(i);
    885                     out.startTag(null, TAG_PROVIDER);
    886                     out.attribute(null, ATTR_VALUE, provider);
    887                     out.endTag(null, TAG_PROVIDER);
    888                 }
    889                 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
    890             }
    891             writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
    892                     permittedAccessiblityServices);
    893             writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
    894             writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
    895             if (hasUserRestrictions()) {
    896                 UserRestrictionsUtils.writeRestrictions(
    897                         out, userRestrictions, TAG_USER_RESTRICTIONS);
    898             }
    899             if (!TextUtils.isEmpty(shortSupportMessage)) {
    900                 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
    901                 out.text(shortSupportMessage.toString());
    902                 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
    903             }
    904             if (!TextUtils.isEmpty(longSupportMessage)) {
    905                 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
    906                 out.text(longSupportMessage.toString());
    907                 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
    908             }
    909             if (parentAdmin != null) {
    910                 out.startTag(null, TAG_PARENT_ADMIN);
    911                 parentAdmin.writeToXml(out);
    912                 out.endTag(null, TAG_PARENT_ADMIN);
    913             }
    914             if (organizationColor != DEF_ORGANIZATION_COLOR) {
    915                 out.startTag(null, TAG_ORGANIZATION_COLOR);
    916                 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
    917                 out.endTag(null, TAG_ORGANIZATION_COLOR);
    918             }
    919             if (organizationName != null) {
    920                 out.startTag(null, TAG_ORGANIZATION_NAME);
    921                 out.text(organizationName);
    922                 out.endTag(null, TAG_ORGANIZATION_NAME);
    923             }
    924         }
    925 
    926         void writePackageListToXml(XmlSerializer out, String outerTag,
    927                 List<String> packageList)
    928                 throws IllegalArgumentException, IllegalStateException, IOException {
    929             if (packageList == null) {
    930                 return;
    931             }
    932 
    933             out.startTag(null, outerTag);
    934             for (String packageName : packageList) {
    935                 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
    936                 out.attribute(null, ATTR_VALUE, packageName);
    937                 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
    938             }
    939             out.endTag(null, outerTag);
    940         }
    941 
    942         void readFromXml(XmlPullParser parser)
    943                 throws XmlPullParserException, IOException {
    944             int outerDepth = parser.getDepth();
    945             int type;
    946             while ((type=parser.next()) != END_DOCUMENT
    947                    && (type != END_TAG || parser.getDepth() > outerDepth)) {
    948                 if (type == END_TAG || type == TEXT) {
    949                     continue;
    950                 }
    951                 String tag = parser.getName();
    952                 if (TAG_POLICIES.equals(tag)) {
    953                     info.readPoliciesFromXml(parser);
    954                 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
    955                     passwordQuality = Integer.parseInt(
    956                             parser.getAttributeValue(null, ATTR_VALUE));
    957                 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
    958                     minimumPasswordLength = Integer.parseInt(
    959                             parser.getAttributeValue(null, ATTR_VALUE));
    960                 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
    961                     passwordHistoryLength = Integer.parseInt(
    962                             parser.getAttributeValue(null, ATTR_VALUE));
    963                 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
    964                     minimumPasswordUpperCase = Integer.parseInt(
    965                             parser.getAttributeValue(null, ATTR_VALUE));
    966                 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
    967                     minimumPasswordLowerCase = Integer.parseInt(
    968                             parser.getAttributeValue(null, ATTR_VALUE));
    969                 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
    970                     minimumPasswordLetters = Integer.parseInt(
    971                             parser.getAttributeValue(null, ATTR_VALUE));
    972                 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
    973                     minimumPasswordNumeric = Integer.parseInt(
    974                             parser.getAttributeValue(null, ATTR_VALUE));
    975                 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
    976                     minimumPasswordSymbols = Integer.parseInt(
    977                             parser.getAttributeValue(null, ATTR_VALUE));
    978                 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
    979                     minimumPasswordNonLetter = Integer.parseInt(
    980                             parser.getAttributeValue(null, ATTR_VALUE));
    981                 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
    982                     maximumTimeToUnlock = Long.parseLong(
    983                             parser.getAttributeValue(null, ATTR_VALUE));
    984                 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
    985                     strongAuthUnlockTimeout = Long.parseLong(
    986                             parser.getAttributeValue(null, ATTR_VALUE));
    987                 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
    988                     maximumFailedPasswordsForWipe = Integer.parseInt(
    989                             parser.getAttributeValue(null, ATTR_VALUE));
    990                 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
    991                     specifiesGlobalProxy = Boolean.parseBoolean(
    992                             parser.getAttributeValue(null, ATTR_VALUE));
    993                 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
    994                     globalProxySpec =
    995                         parser.getAttributeValue(null, ATTR_VALUE);
    996                 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
    997                     globalProxyExclusionList =
    998                         parser.getAttributeValue(null, ATTR_VALUE);
    999                 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
   1000                     passwordExpirationTimeout = Long.parseLong(
   1001                             parser.getAttributeValue(null, ATTR_VALUE));
   1002                 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
   1003                     passwordExpirationDate = Long.parseLong(
   1004                             parser.getAttributeValue(null, ATTR_VALUE));
   1005                 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
   1006                     encryptionRequested = Boolean.parseBoolean(
   1007                             parser.getAttributeValue(null, ATTR_VALUE));
   1008                 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
   1009                     testOnlyAdmin = Boolean.parseBoolean(
   1010                             parser.getAttributeValue(null, ATTR_VALUE));
   1011                 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
   1012                     disableCamera = Boolean.parseBoolean(
   1013                             parser.getAttributeValue(null, ATTR_VALUE));
   1014                 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
   1015                     disableCallerId = Boolean.parseBoolean(
   1016                             parser.getAttributeValue(null, ATTR_VALUE));
   1017                 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
   1018                     disableContactsSearch = Boolean.parseBoolean(
   1019                             parser.getAttributeValue(null, ATTR_VALUE));
   1020                 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
   1021                     disableBluetoothContactSharing = Boolean.parseBoolean(parser
   1022                             .getAttributeValue(null, ATTR_VALUE));
   1023                 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
   1024                     disableScreenCapture = Boolean.parseBoolean(
   1025                             parser.getAttributeValue(null, ATTR_VALUE));
   1026                 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
   1027                     requireAutoTime = Boolean.parseBoolean(
   1028                             parser.getAttributeValue(null, ATTR_VALUE));
   1029                 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
   1030                     forceEphemeralUsers = Boolean.parseBoolean(
   1031                             parser.getAttributeValue(null, ATTR_VALUE));
   1032                 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
   1033                     disabledKeyguardFeatures = Integer.parseInt(
   1034                             parser.getAttributeValue(null, ATTR_VALUE));
   1035                 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
   1036                     accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
   1037                 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
   1038                     trustAgentInfos = getAllTrustAgentInfos(parser, tag);
   1039                 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
   1040                     crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
   1041                 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
   1042                     permittedAccessiblityServices = readPackageList(parser, tag);
   1043                 } else if (TAG_PERMITTED_IMES.equals(tag)) {
   1044                     permittedInputMethods = readPackageList(parser, tag);
   1045                 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
   1046                     keepUninstalledPackages = readPackageList(parser, tag);
   1047                 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
   1048                     UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
   1049                 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
   1050                     type = parser.next();
   1051                     if (type == XmlPullParser.TEXT) {
   1052                         shortSupportMessage = parser.getText();
   1053                     } else {
   1054                         Log.w(LOG_TAG, "Missing text when loading short support message");
   1055                     }
   1056                 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
   1057                     type = parser.next();
   1058                     if (type == XmlPullParser.TEXT) {
   1059                         longSupportMessage = parser.getText();
   1060                     } else {
   1061                         Log.w(LOG_TAG, "Missing text when loading long support message");
   1062                     }
   1063                 } else if (TAG_PARENT_ADMIN.equals(tag)) {
   1064                     Preconditions.checkState(!isParent);
   1065 
   1066                     parentAdmin = new ActiveAdmin(info, /* parent */ true);
   1067                     parentAdmin.readFromXml(parser);
   1068                 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
   1069                     organizationColor = Integer.parseInt(
   1070                             parser.getAttributeValue(null, ATTR_VALUE));
   1071                 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
   1072                     type = parser.next();
   1073                     if (type == XmlPullParser.TEXT) {
   1074                         organizationName = parser.getText();
   1075                     } else {
   1076                         Log.w(LOG_TAG, "Missing text when loading organization name");
   1077                     }
   1078                 } else {
   1079                     Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
   1080                     XmlUtils.skipCurrentTag(parser);
   1081                 }
   1082             }
   1083         }
   1084 
   1085         private List<String> readPackageList(XmlPullParser parser,
   1086                 String tag) throws XmlPullParserException, IOException {
   1087             List<String> result = new ArrayList<String>();
   1088             int outerDepth = parser.getDepth();
   1089             int outerType;
   1090             while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
   1091                     && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   1092                 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
   1093                     continue;
   1094                 }
   1095                 String outerTag = parser.getName();
   1096                 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
   1097                     String packageName = parser.getAttributeValue(null, ATTR_VALUE);
   1098                     if (packageName != null) {
   1099                         result.add(packageName);
   1100                     } else {
   1101                         Slog.w(LOG_TAG, "Package name missing under " + outerTag);
   1102                     }
   1103                 } else {
   1104                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
   1105                 }
   1106             }
   1107             return result;
   1108         }
   1109 
   1110         private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
   1111                 throws XmlPullParserException, IOException {
   1112             int outerDepthDAM = parser.getDepth();
   1113             int typeDAM;
   1114             Set<String> result = new ArraySet<>();
   1115             while ((typeDAM=parser.next()) != END_DOCUMENT
   1116                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
   1117                 if (typeDAM == END_TAG || typeDAM == TEXT) {
   1118                     continue;
   1119                 }
   1120                 String tagDAM = parser.getName();
   1121                 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
   1122                     result.add(parser.getAttributeValue(null, ATTR_VALUE));
   1123                 } else {
   1124                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
   1125                 }
   1126             }
   1127             return result;
   1128         }
   1129 
   1130         private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
   1131                 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
   1132             int outerDepthDAM = parser.getDepth();
   1133             int typeDAM;
   1134             final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
   1135             while ((typeDAM=parser.next()) != END_DOCUMENT
   1136                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
   1137                 if (typeDAM == END_TAG || typeDAM == TEXT) {
   1138                     continue;
   1139                 }
   1140                 String tagDAM = parser.getName();
   1141                 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
   1142                     final String component = parser.getAttributeValue(null, ATTR_VALUE);
   1143                     final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
   1144                     result.put(component, trustAgentInfo);
   1145                 } else {
   1146                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
   1147                 }
   1148             }
   1149             return result;
   1150         }
   1151 
   1152         private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
   1153                 throws XmlPullParserException, IOException  {
   1154             int outerDepthDAM = parser.getDepth();
   1155             int typeDAM;
   1156             TrustAgentInfo result = new TrustAgentInfo(null);
   1157             while ((typeDAM=parser.next()) != END_DOCUMENT
   1158                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
   1159                 if (typeDAM == END_TAG || typeDAM == TEXT) {
   1160                     continue;
   1161                 }
   1162                 String tagDAM = parser.getName();
   1163                 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
   1164                     result.options = PersistableBundle.restoreFromXml(parser);
   1165                 } else {
   1166                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
   1167                 }
   1168             }
   1169             return result;
   1170         }
   1171 
   1172         private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
   1173                 throws XmlPullParserException, IOException  {
   1174             int outerDepthDAM = parser.getDepth();
   1175             int typeDAM;
   1176             ArrayList<String> result = null;
   1177             while ((typeDAM=parser.next()) != END_DOCUMENT
   1178                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
   1179                 if (typeDAM == END_TAG || typeDAM == TEXT) {
   1180                     continue;
   1181                 }
   1182                 String tagDAM = parser.getName();
   1183                 if (TAG_PROVIDER.equals(tagDAM)) {
   1184                     final String provider = parser.getAttributeValue(null, ATTR_VALUE);
   1185                     if (result == null) {
   1186                         result = new ArrayList<>();
   1187                     }
   1188                     result.add(provider);
   1189                 } else {
   1190                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
   1191                 }
   1192             }
   1193             return result;
   1194         }
   1195 
   1196         boolean hasUserRestrictions() {
   1197             return userRestrictions != null && userRestrictions.size() > 0;
   1198         }
   1199 
   1200         Bundle ensureUserRestrictions() {
   1201             if (userRestrictions == null) {
   1202                 userRestrictions = new Bundle();
   1203             }
   1204             return userRestrictions;
   1205         }
   1206 
   1207         void dump(String prefix, PrintWriter pw) {
   1208             pw.print(prefix); pw.print("uid="); pw.println(getUid());
   1209             pw.print(prefix); pw.print("testOnlyAdmin=");
   1210             pw.println(testOnlyAdmin);
   1211             pw.print(prefix); pw.println("policies:");
   1212             ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
   1213             if (pols != null) {
   1214                 for (int i=0; i<pols.size(); i++) {
   1215                     pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
   1216                 }
   1217             }
   1218             pw.print(prefix); pw.print("passwordQuality=0x");
   1219                     pw.println(Integer.toHexString(passwordQuality));
   1220             pw.print(prefix); pw.print("minimumPasswordLength=");
   1221                     pw.println(minimumPasswordLength);
   1222             pw.print(prefix); pw.print("passwordHistoryLength=");
   1223                     pw.println(passwordHistoryLength);
   1224             pw.print(prefix); pw.print("minimumPasswordUpperCase=");
   1225                     pw.println(minimumPasswordUpperCase);
   1226             pw.print(prefix); pw.print("minimumPasswordLowerCase=");
   1227                     pw.println(minimumPasswordLowerCase);
   1228             pw.print(prefix); pw.print("minimumPasswordLetters=");
   1229                     pw.println(minimumPasswordLetters);
   1230             pw.print(prefix); pw.print("minimumPasswordNumeric=");
   1231                     pw.println(minimumPasswordNumeric);
   1232             pw.print(prefix); pw.print("minimumPasswordSymbols=");
   1233                     pw.println(minimumPasswordSymbols);
   1234             pw.print(prefix); pw.print("minimumPasswordNonLetter=");
   1235                     pw.println(minimumPasswordNonLetter);
   1236             pw.print(prefix); pw.print("maximumTimeToUnlock=");
   1237                     pw.println(maximumTimeToUnlock);
   1238             pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
   1239                     pw.println(strongAuthUnlockTimeout);
   1240             pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
   1241                     pw.println(maximumFailedPasswordsForWipe);
   1242             pw.print(prefix); pw.print("specifiesGlobalProxy=");
   1243                     pw.println(specifiesGlobalProxy);
   1244             pw.print(prefix); pw.print("passwordExpirationTimeout=");
   1245                     pw.println(passwordExpirationTimeout);
   1246             pw.print(prefix); pw.print("passwordExpirationDate=");
   1247                     pw.println(passwordExpirationDate);
   1248             if (globalProxySpec != null) {
   1249                 pw.print(prefix); pw.print("globalProxySpec=");
   1250                         pw.println(globalProxySpec);
   1251             }
   1252             if (globalProxyExclusionList != null) {
   1253                 pw.print(prefix); pw.print("globalProxyEclusionList=");
   1254                         pw.println(globalProxyExclusionList);
   1255             }
   1256             pw.print(prefix); pw.print("encryptionRequested=");
   1257                     pw.println(encryptionRequested);
   1258             pw.print(prefix); pw.print("disableCamera=");
   1259                     pw.println(disableCamera);
   1260             pw.print(prefix); pw.print("disableCallerId=");
   1261                     pw.println(disableCallerId);
   1262             pw.print(prefix); pw.print("disableContactsSearch=");
   1263                     pw.println(disableContactsSearch);
   1264             pw.print(prefix); pw.print("disableBluetoothContactSharing=");
   1265                     pw.println(disableBluetoothContactSharing);
   1266             pw.print(prefix); pw.print("disableScreenCapture=");
   1267                     pw.println(disableScreenCapture);
   1268             pw.print(prefix); pw.print("requireAutoTime=");
   1269                     pw.println(requireAutoTime);
   1270             pw.print(prefix); pw.print("forceEphemeralUsers=");
   1271                     pw.println(forceEphemeralUsers);
   1272             pw.print(prefix); pw.print("disabledKeyguardFeatures=");
   1273                     pw.println(disabledKeyguardFeatures);
   1274             pw.print(prefix); pw.print("crossProfileWidgetProviders=");
   1275                     pw.println(crossProfileWidgetProviders);
   1276             if (permittedAccessiblityServices != null) {
   1277                 pw.print(prefix); pw.print("permittedAccessibilityServices=");
   1278                     pw.println(permittedAccessiblityServices);
   1279             }
   1280             if (permittedInputMethods != null) {
   1281                 pw.print(prefix); pw.print("permittedInputMethods=");
   1282                     pw.println(permittedInputMethods);
   1283             }
   1284             if (keepUninstalledPackages != null) {
   1285                 pw.print(prefix); pw.print("keepUninstalledPackages=");
   1286                     pw.println(keepUninstalledPackages);
   1287             }
   1288             pw.print(prefix); pw.print("organizationColor=");
   1289                     pw.println(organizationColor);
   1290             if (organizationName != null) {
   1291                 pw.print(prefix); pw.print("organizationName=");
   1292                     pw.println(organizationName);
   1293             }
   1294             pw.print(prefix); pw.println("userRestrictions:");
   1295             UserRestrictionsUtils.dumpRestrictions(pw, prefix + "  ", userRestrictions);
   1296             pw.print(prefix); pw.print("isParent=");
   1297                     pw.println(isParent);
   1298             if (parentAdmin != null) {
   1299                 pw.print(prefix);  pw.println("parentAdmin:");
   1300                 parentAdmin.dump(prefix + "  ", pw);
   1301             }
   1302         }
   1303     }
   1304 
   1305     private void handlePackagesChanged(String packageName, int userHandle) {
   1306         boolean removed = false;
   1307         if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
   1308         DevicePolicyData policy = getUserData(userHandle);
   1309         synchronized (this) {
   1310             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
   1311                 ActiveAdmin aa = policy.mAdminList.get(i);
   1312                 try {
   1313                     // If we're checking all packages or if the specific one we're checking matches,
   1314                     // then check if the package and receiver still exist.
   1315                     final String adminPackage = aa.info.getPackageName();
   1316                     if (packageName == null || packageName.equals(adminPackage)) {
   1317                         if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
   1318                                 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
   1319                                         PackageManager.MATCH_DIRECT_BOOT_AWARE
   1320                                                 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
   1321                                         userHandle) == null) {
   1322                             removed = true;
   1323                             policy.mAdminList.remove(i);
   1324                             policy.mAdminMap.remove(aa.info.getComponent());
   1325                         }
   1326                     }
   1327                 } catch (RemoteException re) {
   1328                     // Shouldn't happen
   1329                 }
   1330             }
   1331             if (removed) {
   1332                 validatePasswordOwnerLocked(policy);
   1333                 saveSettingsLocked(policy.mUserHandle);
   1334             }
   1335 
   1336             // Check if delegated cert installer or app restrictions managing packages are removed.
   1337             if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
   1338                 policy.mDelegatedCertInstallerPackage = null;
   1339                 saveSettingsLocked(policy.mUserHandle);
   1340             }
   1341             if (isRemovedPackage(
   1342                     packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
   1343                 policy.mApplicationRestrictionsManagingPackage = null;
   1344                 saveSettingsLocked(policy.mUserHandle);
   1345             }
   1346         }
   1347         if (removed) {
   1348             // The removed admin might have disabled camera, so update user restrictions.
   1349             pushUserRestrictions(userHandle);
   1350         }
   1351     }
   1352 
   1353     private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
   1354         try {
   1355             return targetPackage != null
   1356                     && (changedPackage == null || changedPackage.equals(targetPackage))
   1357                     && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
   1358         } catch (RemoteException e) {
   1359             // Shouldn't happen
   1360         }
   1361 
   1362         return false;
   1363     }
   1364 
   1365     /**
   1366      * Unit test will subclass it to inject mocks.
   1367      */
   1368     @VisibleForTesting
   1369     static class Injector {
   1370 
   1371         private final Context mContext;
   1372 
   1373         Injector(Context context) {
   1374             mContext = context;
   1375         }
   1376 
   1377         Owners newOwners() {
   1378             return new Owners(getUserManager(), getUserManagerInternal(),
   1379                     getPackageManagerInternal());
   1380         }
   1381 
   1382         UserManager getUserManager() {
   1383             return UserManager.get(mContext);
   1384         }
   1385 
   1386         UserManagerInternal getUserManagerInternal() {
   1387             return LocalServices.getService(UserManagerInternal.class);
   1388         }
   1389 
   1390         PackageManagerInternal getPackageManagerInternal() {
   1391             return LocalServices.getService(PackageManagerInternal.class);
   1392         }
   1393 
   1394         NotificationManager getNotificationManager() {
   1395             return mContext.getSystemService(NotificationManager.class);
   1396         }
   1397 
   1398         PowerManagerInternal getPowerManagerInternal() {
   1399             return LocalServices.getService(PowerManagerInternal.class);
   1400         }
   1401 
   1402         TelephonyManager getTelephonyManager() {
   1403             return TelephonyManager.from(mContext);
   1404         }
   1405 
   1406         TrustManager getTrustManager() {
   1407             return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
   1408         }
   1409 
   1410         IWindowManager getIWindowManager() {
   1411             return IWindowManager.Stub
   1412                     .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
   1413         }
   1414 
   1415         IActivityManager getIActivityManager() {
   1416             return ActivityManagerNative.getDefault();
   1417         }
   1418 
   1419         IPackageManager getIPackageManager() {
   1420             return AppGlobals.getPackageManager();
   1421         }
   1422 
   1423         IBackupManager getIBackupManager() {
   1424             return IBackupManager.Stub.asInterface(
   1425                     ServiceManager.getService(Context.BACKUP_SERVICE));
   1426         }
   1427 
   1428         IAudioService getIAudioService() {
   1429             return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
   1430         }
   1431 
   1432         LockPatternUtils newLockPatternUtils() {
   1433             return new LockPatternUtils(mContext);
   1434         }
   1435 
   1436         boolean storageManagerIsFileBasedEncryptionEnabled() {
   1437             return StorageManager.isFileEncryptedNativeOnly();
   1438         }
   1439 
   1440         boolean storageManagerIsNonDefaultBlockEncrypted() {
   1441             long identity = Binder.clearCallingIdentity();
   1442             try {
   1443                 return StorageManager.isNonDefaultBlockEncrypted();
   1444             } finally {
   1445                 Binder.restoreCallingIdentity(identity);
   1446             }
   1447         }
   1448 
   1449         boolean storageManagerIsEncrypted() {
   1450             return StorageManager.isEncrypted();
   1451         }
   1452 
   1453         boolean storageManagerIsEncryptable() {
   1454             return StorageManager.isEncryptable();
   1455         }
   1456 
   1457         Looper getMyLooper() {
   1458             return Looper.myLooper();
   1459         }
   1460 
   1461         WifiManager getWifiManager() {
   1462             return mContext.getSystemService(WifiManager.class);
   1463         }
   1464 
   1465         long binderClearCallingIdentity() {
   1466             return Binder.clearCallingIdentity();
   1467         }
   1468 
   1469         void binderRestoreCallingIdentity(long token) {
   1470             Binder.restoreCallingIdentity(token);
   1471         }
   1472 
   1473         int binderGetCallingUid() {
   1474             return Binder.getCallingUid();
   1475         }
   1476 
   1477         int binderGetCallingPid() {
   1478             return Binder.getCallingPid();
   1479         }
   1480 
   1481         UserHandle binderGetCallingUserHandle() {
   1482             return Binder.getCallingUserHandle();
   1483         }
   1484 
   1485         boolean binderIsCallingUidMyUid() {
   1486             return getCallingUid() == Process.myUid();
   1487         }
   1488 
   1489         final int userHandleGetCallingUserId() {
   1490             return UserHandle.getUserId(binderGetCallingUid());
   1491         }
   1492 
   1493         File environmentGetUserSystemDirectory(int userId) {
   1494             return Environment.getUserSystemDirectory(userId);
   1495         }
   1496 
   1497         void powerManagerGoToSleep(long time, int reason, int flags) {
   1498             mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
   1499         }
   1500 
   1501         void powerManagerReboot(String reason) {
   1502             mContext.getSystemService(PowerManager.class).reboot(reason);
   1503         }
   1504 
   1505         boolean systemPropertiesGetBoolean(String key, boolean def) {
   1506             return SystemProperties.getBoolean(key, def);
   1507         }
   1508 
   1509         long systemPropertiesGetLong(String key, long def) {
   1510             return SystemProperties.getLong(key, def);
   1511         }
   1512 
   1513         String systemPropertiesGet(String key, String def) {
   1514             return SystemProperties.get(key, def);
   1515         }
   1516 
   1517         String systemPropertiesGet(String key) {
   1518             return SystemProperties.get(key);
   1519         }
   1520 
   1521         void systemPropertiesSet(String key, String value) {
   1522             SystemProperties.set(key, value);
   1523         }
   1524 
   1525         boolean userManagerIsSplitSystemUser() {
   1526             return UserManager.isSplitSystemUser();
   1527         }
   1528 
   1529         String getDevicePolicyFilePathForSystemUser() {
   1530             return "/data/system/";
   1531         }
   1532 
   1533         void registerContentObserver(Uri uri, boolean notifyForDescendents,
   1534                 ContentObserver observer, int userHandle) {
   1535             mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
   1536                     observer, userHandle);
   1537         }
   1538 
   1539         int settingsSecureGetIntForUser(String name, int def, int userHandle) {
   1540             return Settings.Secure.getIntForUser(mContext.getContentResolver(),
   1541                     name, def, userHandle);
   1542         }
   1543 
   1544         void settingsSecurePutIntForUser(String name, int value, int userHandle) {
   1545             Settings.Secure.putIntForUser(mContext.getContentResolver(),
   1546                     name, value, userHandle);
   1547         }
   1548 
   1549         void settingsSecurePutStringForUser(String name, String value, int userHandle) {
   1550             Settings.Secure.putStringForUser(mContext.getContentResolver(),
   1551                     name, value, userHandle);
   1552         }
   1553 
   1554         void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
   1555             Settings.Global.putStringForUser(mContext.getContentResolver(),
   1556                     name, value, userHandle);
   1557         }
   1558 
   1559         void settingsSecurePutInt(String name, int value) {
   1560             Settings.Secure.putInt(mContext.getContentResolver(), name, value);
   1561         }
   1562 
   1563         int settingsGlobalGetInt(String name, int def) {
   1564             return Settings.Global.getInt(mContext.getContentResolver(), name, def);
   1565         }
   1566 
   1567         void settingsGlobalPutInt(String name, int value) {
   1568             Settings.Global.putInt(mContext.getContentResolver(), name, value);
   1569         }
   1570 
   1571         void settingsSecurePutString(String name, String value) {
   1572             Settings.Secure.putString(mContext.getContentResolver(), name, value);
   1573         }
   1574 
   1575         void settingsGlobalPutString(String name, String value) {
   1576             Settings.Global.putString(mContext.getContentResolver(), name, value);
   1577         }
   1578 
   1579         void securityLogSetLoggingEnabledProperty(boolean enabled) {
   1580             SecurityLog.setLoggingEnabledProperty(enabled);
   1581         }
   1582 
   1583         boolean securityLogGetLoggingEnabledProperty() {
   1584             return SecurityLog.getLoggingEnabledProperty();
   1585         }
   1586 
   1587         boolean securityLogIsLoggingEnabled() {
   1588             return SecurityLog.isLoggingEnabled();
   1589         }
   1590     }
   1591 
   1592     /**
   1593      * Instantiates the service.
   1594      */
   1595     public DevicePolicyManagerService(Context context) {
   1596         this(new Injector(context));
   1597     }
   1598 
   1599     @VisibleForTesting
   1600     DevicePolicyManagerService(Injector injector) {
   1601         mInjector = injector;
   1602         mContext = Preconditions.checkNotNull(injector.mContext);
   1603         mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
   1604         mOwners = Preconditions.checkNotNull(injector.newOwners());
   1605 
   1606         mUserManager = Preconditions.checkNotNull(injector.getUserManager());
   1607         mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
   1608         mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
   1609         mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
   1610 
   1611         mLocalService = new LocalService();
   1612         mLockPatternUtils = injector.newLockPatternUtils();
   1613 
   1614         mSecurityLogMonitor = new SecurityLogMonitor(this);
   1615 
   1616         mHasFeature = mContext.getPackageManager()
   1617                 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
   1618         if (!mHasFeature) {
   1619             // Skip the rest of the initialization
   1620             return;
   1621         }
   1622         IntentFilter filter = new IntentFilter();
   1623         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
   1624         filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
   1625         filter.addAction(Intent.ACTION_USER_ADDED);
   1626         filter.addAction(Intent.ACTION_USER_REMOVED);
   1627         filter.addAction(Intent.ACTION_USER_STARTED);
   1628         filter.addAction(Intent.ACTION_USER_UNLOCKED);
   1629         filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
   1630         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
   1631         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
   1632         filter = new IntentFilter();
   1633         filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
   1634         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
   1635         filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
   1636         filter.addAction(Intent.ACTION_PACKAGE_ADDED);
   1637         filter.addDataScheme("package");
   1638         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
   1639         filter = new IntentFilter();
   1640         filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
   1641         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
   1642 
   1643         LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
   1644     }
   1645 
   1646     /**
   1647      * Creates and loads the policy data from xml.
   1648      * @param userHandle the user for whom to load the policy data
   1649      * @return
   1650      */
   1651     @NonNull
   1652     DevicePolicyData getUserData(int userHandle) {
   1653         synchronized (this) {
   1654             DevicePolicyData policy = mUserData.get(userHandle);
   1655             if (policy == null) {
   1656                 policy = new DevicePolicyData(userHandle);
   1657                 mUserData.append(userHandle, policy);
   1658                 loadSettingsLocked(policy, userHandle);
   1659             }
   1660             return policy;
   1661         }
   1662     }
   1663 
   1664     /**
   1665      * Creates and loads the policy data from xml for data that is shared between
   1666      * various profiles of a user. In contrast to {@link #getUserData(int)}
   1667      * it allows access to data of users other than the calling user.
   1668      *
   1669      * This function should only be used for shared data, e.g. everything regarding
   1670      * passwords and should be removed once multiple screen locks are present.
   1671      * @param userHandle the user for whom to load the policy data
   1672      * @return
   1673      */
   1674     DevicePolicyData getUserDataUnchecked(int userHandle) {
   1675         long ident = mInjector.binderClearCallingIdentity();
   1676         try {
   1677             return getUserData(userHandle);
   1678         } finally {
   1679             mInjector.binderRestoreCallingIdentity(ident);
   1680         }
   1681     }
   1682 
   1683     void removeUserData(int userHandle) {
   1684         synchronized (this) {
   1685             if (userHandle == UserHandle.USER_SYSTEM) {
   1686                 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
   1687                 return;
   1688             }
   1689             mOwners.removeProfileOwner(userHandle);
   1690             mOwners.writeProfileOwner(userHandle);
   1691 
   1692             DevicePolicyData policy = mUserData.get(userHandle);
   1693             if (policy != null) {
   1694                 mUserData.remove(userHandle);
   1695             }
   1696             File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
   1697                     DEVICE_POLICIES_XML);
   1698             policyFile.delete();
   1699             Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
   1700         }
   1701         updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
   1702     }
   1703 
   1704     void loadOwners() {
   1705         synchronized (this) {
   1706             mOwners.load();
   1707             setDeviceOwnerSystemPropertyLocked();
   1708             findOwnerComponentIfNecessaryLocked();
   1709             migrateUserRestrictionsIfNecessaryLocked();
   1710 
   1711             // TODO PO may not have a class name either due to b/17652534.  Address that too.
   1712 
   1713             updateDeviceOwnerLocked();
   1714         }
   1715     }
   1716 
   1717     private void setDeviceOwnerSystemPropertyLocked() {
   1718         // Device owner may still be provisioned, do not set the read-only system property yet.
   1719         if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
   1720             return;
   1721         }
   1722         // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
   1723         // always false at this point.
   1724         if (StorageManager.inCryptKeeperBounce()) {
   1725             return;
   1726         }
   1727 
   1728         if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
   1729             Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
   1730         } else {
   1731             if (mOwners.hasDeviceOwner()) {
   1732                 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
   1733                 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
   1734                 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
   1735                 if (mInjector.securityLogGetLoggingEnabledProperty()) {
   1736                     mSecurityLogMonitor.start();
   1737                 }
   1738             } else {
   1739                 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
   1740                 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
   1741             }
   1742         }
   1743     }
   1744 
   1745     private void findOwnerComponentIfNecessaryLocked() {
   1746         if (!mOwners.hasDeviceOwner()) {
   1747             return;
   1748         }
   1749         final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
   1750 
   1751         if (!TextUtils.isEmpty(doComponentName.getClassName())) {
   1752             return; // Already a full component name.
   1753         }
   1754 
   1755         final ComponentName doComponent = findAdminComponentWithPackageLocked(
   1756                 doComponentName.getPackageName(),
   1757                 mOwners.getDeviceOwnerUserId());
   1758         if (doComponent == null) {
   1759             Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
   1760         } else {
   1761             mOwners.setDeviceOwnerWithRestrictionsMigrated(
   1762                     doComponent,
   1763                     mOwners.getDeviceOwnerName(),
   1764                     mOwners.getDeviceOwnerUserId(),
   1765                     !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
   1766             mOwners.writeDeviceOwner();
   1767             if (VERBOSE_LOG) {
   1768                 Log.v(LOG_TAG, "Device owner component filled in");
   1769             }
   1770         }
   1771     }
   1772 
   1773     /**
   1774      * We didn't use to persist user restrictions for each owners but only persisted in user
   1775      * manager.
   1776      */
   1777     private void migrateUserRestrictionsIfNecessaryLocked() {
   1778         boolean migrated = false;
   1779         // Migrate for the DO.  Basically all restrictions should be considered to be set by DO,
   1780         // except for the "system controlled" ones.
   1781         if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
   1782             if (VERBOSE_LOG) {
   1783                 Log.v(LOG_TAG, "Migrating DO user restrictions");
   1784             }
   1785             migrated = true;
   1786 
   1787             // Migrate user 0 restrictions to DO.
   1788             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
   1789 
   1790             migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
   1791                     /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
   1792 
   1793             // Push DO user restrictions to user manager.
   1794             pushUserRestrictions(UserHandle.USER_SYSTEM);
   1795 
   1796             mOwners.setDeviceOwnerUserRestrictionsMigrated();
   1797         }
   1798 
   1799         // Migrate for POs.
   1800 
   1801         // The following restrictions can be set on secondary users by the device owner, so we
   1802         // assume they're not from the PO.
   1803         final Set<String> secondaryUserExceptionList = Sets.newArraySet(
   1804                 UserManager.DISALLOW_OUTGOING_CALLS,
   1805                 UserManager.DISALLOW_SMS);
   1806 
   1807         for (UserInfo ui : mUserManager.getUsers()) {
   1808             final int userId = ui.id;
   1809             if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
   1810                 if (VERBOSE_LOG) {
   1811                     Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
   1812                 }
   1813                 migrated = true;
   1814 
   1815                 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
   1816 
   1817                 final Set<String> exceptionList =
   1818                         (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
   1819 
   1820                 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
   1821                         exceptionList, /* isDeviceOwner =*/ false);
   1822 
   1823                 // Note if a secondary user has no PO but has a DA that disables camera, we
   1824                 // don't get here and won't push the camera user restriction to UserManager
   1825                 // here.  That's okay because we'll push user restrictions anyway when a user
   1826                 // starts.  But we still do it because we want to let user manager persist
   1827                 // upon migration.
   1828                 pushUserRestrictions(userId);
   1829 
   1830                 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
   1831             }
   1832         }
   1833         if (VERBOSE_LOG && migrated) {
   1834             Log.v(LOG_TAG, "User restrictions migrated.");
   1835         }
   1836     }
   1837 
   1838     private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
   1839             Set<String> exceptionList, boolean isDeviceOwner) {
   1840         final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
   1841                 user.getIdentifier());
   1842 
   1843         final Bundle newBaseRestrictions = new Bundle();
   1844         final Bundle newOwnerRestrictions = new Bundle();
   1845 
   1846         for (String key : origRestrictions.keySet()) {
   1847             if (!origRestrictions.getBoolean(key)) {
   1848                 continue;
   1849             }
   1850             final boolean canOwnerChange = isDeviceOwner
   1851                     ? UserRestrictionsUtils.canDeviceOwnerChange(key)
   1852                     : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
   1853 
   1854             if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
   1855                 newBaseRestrictions.putBoolean(key, true);
   1856             } else {
   1857                 newOwnerRestrictions.putBoolean(key, true);
   1858             }
   1859         }
   1860 
   1861         if (VERBOSE_LOG) {
   1862             Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
   1863             Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
   1864             Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
   1865         }
   1866         mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
   1867                 newBaseRestrictions);
   1868 
   1869         if (admin != null) {
   1870             admin.ensureUserRestrictions().clear();
   1871             admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
   1872         } else {
   1873             Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
   1874         }
   1875         saveSettingsLocked(user.getIdentifier());
   1876     }
   1877 
   1878     private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
   1879         final DevicePolicyData policy = getUserData(userId);
   1880         final int n = policy.mAdminList.size();
   1881         ComponentName found = null;
   1882         int nFound = 0;
   1883         for (int i = 0; i < n; i++) {
   1884             final ActiveAdmin admin = policy.mAdminList.get(i);
   1885             if (packageName.equals(admin.info.getPackageName())) {
   1886                 // Found!
   1887                 if (nFound == 0) {
   1888                     found = admin.info.getComponent();
   1889                 }
   1890                 nFound++;
   1891             }
   1892         }
   1893         if (nFound > 1) {
   1894             Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
   1895         }
   1896         return found;
   1897     }
   1898 
   1899     /**
   1900      * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
   1901      * reminders.  Clears alarm if no expirations are configured.
   1902      */
   1903     private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
   1904         final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
   1905         final long now = System.currentTimeMillis();
   1906         final long timeToExpire = expiration - now;
   1907         final long alarmTime;
   1908         if (expiration == 0) {
   1909             // No expirations are currently configured:  Cancel alarm.
   1910             alarmTime = 0;
   1911         } else if (timeToExpire <= 0) {
   1912             // The password has already expired:  Repeat every 24 hours.
   1913             alarmTime = now + MS_PER_DAY;
   1914         } else {
   1915             // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
   1916             // the expiration time.
   1917             long alarmInterval = timeToExpire % MS_PER_DAY;
   1918             if (alarmInterval == 0) {
   1919                 alarmInterval = MS_PER_DAY;
   1920             }
   1921             alarmTime = now + alarmInterval;
   1922         }
   1923 
   1924         long token = mInjector.binderClearCallingIdentity();
   1925         try {
   1926             int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
   1927             AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   1928             PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
   1929                     new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
   1930                     PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
   1931                     UserHandle.of(affectedUserHandle));
   1932             am.cancel(pi);
   1933             if (alarmTime != 0) {
   1934                 am.set(AlarmManager.RTC, alarmTime, pi);
   1935             }
   1936         } finally {
   1937             mInjector.binderRestoreCallingIdentity(token);
   1938         }
   1939     }
   1940 
   1941     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
   1942         ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
   1943         if (admin != null
   1944                 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
   1945                 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
   1946             return admin;
   1947         }
   1948         return null;
   1949     }
   1950 
   1951     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
   1952         if (parent) {
   1953             enforceManagedProfile(userHandle, "call APIs on the parent profile");
   1954         }
   1955         ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   1956         if (admin != null && parent) {
   1957             admin = admin.getParentActiveAdmin();
   1958         }
   1959         return admin;
   1960     }
   1961 
   1962     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
   1963             throws SecurityException {
   1964         final int callingUid = mInjector.binderGetCallingUid();
   1965 
   1966         ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
   1967         if (result != null) {
   1968             return result;
   1969         }
   1970 
   1971         if (who != null) {
   1972             final int userId = UserHandle.getUserId(callingUid);
   1973             final DevicePolicyData policy = getUserData(userId);
   1974             ActiveAdmin admin = policy.mAdminMap.get(who);
   1975             if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
   1976                 throw new SecurityException("Admin " + admin.info.getComponent()
   1977                          + " does not own the device");
   1978             }
   1979             if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
   1980                 throw new SecurityException("Admin " + admin.info.getComponent()
   1981                         + " does not own the profile");
   1982             }
   1983             throw new SecurityException("Admin " + admin.info.getComponent()
   1984                     + " did not specify uses-policy for: "
   1985                     + admin.info.getTagForPolicy(reqPolicy));
   1986         } else {
   1987             throw new SecurityException("No active admin owned by uid "
   1988                     + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
   1989         }
   1990     }
   1991 
   1992     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
   1993             throws SecurityException {
   1994         if (parent) {
   1995             enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
   1996                     "call APIs on the parent profile");
   1997         }
   1998         ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
   1999         return parent ? admin.getParentActiveAdmin() : admin;
   2000     }
   2001     /**
   2002      * Find the admin for the component and userId bit of the uid, then check
   2003      * the admin's uid matches the uid.
   2004      */
   2005     private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
   2006         final int userId = UserHandle.getUserId(uid);
   2007         final DevicePolicyData policy = getUserData(userId);
   2008         ActiveAdmin admin = policy.mAdminMap.get(who);
   2009         if (admin == null) {
   2010             throw new SecurityException("No active admin " + who);
   2011         }
   2012         if (admin.getUid() != uid) {
   2013             throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
   2014         }
   2015         return admin;
   2016     }
   2017 
   2018     private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
   2019             int uid) {
   2020         // Try to find an admin which can use reqPolicy
   2021         final int userId = UserHandle.getUserId(uid);
   2022         final DevicePolicyData policy = getUserData(userId);
   2023         if (who != null) {
   2024             ActiveAdmin admin = policy.mAdminMap.get(who);
   2025             if (admin == null) {
   2026                 throw new SecurityException("No active admin " + who);
   2027             }
   2028             if (admin.getUid() != uid) {
   2029                 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
   2030             }
   2031             if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
   2032                 return admin;
   2033             }
   2034         } else {
   2035             for (ActiveAdmin admin : policy.mAdminList) {
   2036                 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
   2037                         userId)) {
   2038                     return admin;
   2039                 }
   2040             }
   2041         }
   2042 
   2043         return null;
   2044     }
   2045 
   2046     @VisibleForTesting
   2047     boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
   2048             int userId) {
   2049         final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
   2050         final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
   2051 
   2052         if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
   2053             return ownsDevice;
   2054         } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
   2055             // DO always has the PO power.
   2056             return ownsDevice || ownsProfile;
   2057         } else {
   2058             return admin.info.usesPolicy(reqPolicy);
   2059         }
   2060     }
   2061 
   2062     void sendAdminCommandLocked(ActiveAdmin admin, String action) {
   2063         sendAdminCommandLocked(admin, action, null);
   2064     }
   2065 
   2066     void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
   2067         sendAdminCommandLocked(admin, action, null, result);
   2068     }
   2069 
   2070     /**
   2071      * Send an update to one specific admin, get notified when that admin returns a result.
   2072      */
   2073     void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
   2074             BroadcastReceiver result) {
   2075         Intent intent = new Intent(action);
   2076         intent.setComponent(admin.info.getComponent());
   2077         if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
   2078             intent.putExtra("expiration", admin.passwordExpirationDate);
   2079         }
   2080         if (adminExtras != null) {
   2081             intent.putExtras(adminExtras);
   2082         }
   2083         if (result != null) {
   2084             mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
   2085                     null, result, mHandler, Activity.RESULT_OK, null, null);
   2086         } else {
   2087             mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
   2088         }
   2089     }
   2090 
   2091     /**
   2092      * Send an update to all admins of a user that enforce a specified policy.
   2093      */
   2094     void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
   2095         final DevicePolicyData policy = getUserData(userHandle);
   2096         final int count = policy.mAdminList.size();
   2097         if (count > 0) {
   2098             for (int i = 0; i < count; i++) {
   2099                 final ActiveAdmin admin = policy.mAdminList.get(i);
   2100                 if (admin.info.usesPolicy(reqPolicy)) {
   2101                     sendAdminCommandLocked(admin, action);
   2102                 }
   2103             }
   2104         }
   2105     }
   2106 
   2107     /**
   2108      * Send an update intent to all admins of a user and its profiles. Only send to admins that
   2109      * enforce a specified policy.
   2110      */
   2111     private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
   2112             int userHandle) {
   2113         int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
   2114         for (int profileId : profileIds) {
   2115             sendAdminCommandLocked(action, reqPolicy, profileId);
   2116         }
   2117     }
   2118 
   2119     /**
   2120      * Sends a broadcast to each profile that share the password unlock with the given user id.
   2121      */
   2122     private void sendAdminCommandForLockscreenPoliciesLocked(
   2123             String action, int reqPolicy, int userHandle) {
   2124         if (isSeparateProfileChallengeEnabled(userHandle)) {
   2125             sendAdminCommandLocked(action, reqPolicy, userHandle);
   2126         } else {
   2127             sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
   2128         }
   2129     }
   2130 
   2131     void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
   2132         final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
   2133         DevicePolicyData policy = getUserData(userHandle);
   2134         if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
   2135             policy.mRemovingAdmins.add(adminReceiver);
   2136             sendAdminCommandLocked(admin,
   2137                     DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
   2138                     new BroadcastReceiver() {
   2139                         @Override
   2140                         public void onReceive(Context context, Intent intent) {
   2141                             removeAdminArtifacts(adminReceiver, userHandle);
   2142                             removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
   2143                         }
   2144                     });
   2145         }
   2146     }
   2147 
   2148 
   2149     public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
   2150             boolean throwForMissiongPermission) {
   2151         if (!mHasFeature) {
   2152             return null;
   2153         }
   2154         enforceFullCrossUsersPermission(userHandle);
   2155         ActivityInfo ai = null;
   2156         try {
   2157             ai = mIPackageManager.getReceiverInfo(adminName,
   2158                     PackageManager.GET_META_DATA |
   2159                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
   2160                     PackageManager.MATCH_DIRECT_BOOT_AWARE |
   2161                     PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
   2162         } catch (RemoteException e) {
   2163             // shouldn't happen.
   2164         }
   2165         if (ai == null) {
   2166             throw new IllegalArgumentException("Unknown admin: " + adminName);
   2167         }
   2168 
   2169         if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
   2170             final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
   2171                     + permission.BIND_DEVICE_ADMIN;
   2172             Slog.w(LOG_TAG, message);
   2173             if (throwForMissiongPermission &&
   2174                     ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
   2175                 throw new IllegalArgumentException(message);
   2176             }
   2177         }
   2178 
   2179         try {
   2180             return new DeviceAdminInfo(mContext, ai);
   2181         } catch (XmlPullParserException | IOException e) {
   2182             Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
   2183                     e);
   2184             return null;
   2185         }
   2186     }
   2187 
   2188     private JournaledFile makeJournaledFile(int userHandle) {
   2189         final String base = userHandle == UserHandle.USER_SYSTEM
   2190                 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
   2191                 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
   2192                         DEVICE_POLICIES_XML).getAbsolutePath();
   2193         if (VERBOSE_LOG) {
   2194             Log.v(LOG_TAG, "Opening " + base);
   2195         }
   2196         return new JournaledFile(new File(base), new File(base + ".tmp"));
   2197     }
   2198 
   2199     private void saveSettingsLocked(int userHandle) {
   2200         DevicePolicyData policy = getUserData(userHandle);
   2201         JournaledFile journal = makeJournaledFile(userHandle);
   2202         FileOutputStream stream = null;
   2203         try {
   2204             stream = new FileOutputStream(journal.chooseForWrite(), false);
   2205             XmlSerializer out = new FastXmlSerializer();
   2206             out.setOutput(stream, StandardCharsets.UTF_8.name());
   2207             out.startDocument(null, true);
   2208 
   2209             out.startTag(null, "policies");
   2210             if (policy.mRestrictionsProvider != null) {
   2211                 out.attribute(null, ATTR_PERMISSION_PROVIDER,
   2212                         policy.mRestrictionsProvider.flattenToString());
   2213             }
   2214             if (policy.mUserSetupComplete) {
   2215                 out.attribute(null, ATTR_SETUP_COMPLETE,
   2216                         Boolean.toString(true));
   2217             }
   2218             if (policy.mDeviceProvisioningConfigApplied) {
   2219                 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
   2220                         Boolean.toString(true));
   2221             }
   2222             if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
   2223                 out.attribute(null, ATTR_PROVISIONING_STATE,
   2224                         Integer.toString(policy.mUserProvisioningState));
   2225             }
   2226             if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
   2227                 out.attribute(null, ATTR_PERMISSION_POLICY,
   2228                         Integer.toString(policy.mPermissionPolicy));
   2229             }
   2230             if (policy.mDelegatedCertInstallerPackage != null) {
   2231                 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
   2232                         policy.mDelegatedCertInstallerPackage);
   2233             }
   2234             if (policy.mApplicationRestrictionsManagingPackage != null) {
   2235                 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
   2236                         policy.mApplicationRestrictionsManagingPackage);
   2237             }
   2238 
   2239             final int N = policy.mAdminList.size();
   2240             for (int i=0; i<N; i++) {
   2241                 ActiveAdmin ap = policy.mAdminList.get(i);
   2242                 if (ap != null) {
   2243                     out.startTag(null, "admin");
   2244                     out.attribute(null, "name", ap.info.getComponent().flattenToString());
   2245                     ap.writeToXml(out);
   2246                     out.endTag(null, "admin");
   2247                 }
   2248             }
   2249 
   2250             if (policy.mPasswordOwner >= 0) {
   2251                 out.startTag(null, "password-owner");
   2252                 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
   2253                 out.endTag(null, "password-owner");
   2254             }
   2255 
   2256             if (policy.mFailedPasswordAttempts != 0) {
   2257                 out.startTag(null, "failed-password-attempts");
   2258                 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
   2259                 out.endTag(null, "failed-password-attempts");
   2260             }
   2261 
   2262             if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
   2263                     || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
   2264                     || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
   2265                     || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
   2266                 out.startTag(null, "active-password");
   2267                 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
   2268                 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
   2269                 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
   2270                 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
   2271                 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
   2272                 out.attribute(null, "numeric", Integer
   2273                         .toString(policy.mActivePasswordNumeric));
   2274                 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
   2275                 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
   2276                 out.endTag(null, "active-password");
   2277             }
   2278 
   2279             for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
   2280                 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
   2281                 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
   2282                 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
   2283             }
   2284 
   2285             for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
   2286                 String component = policy.mLockTaskPackages.get(i);
   2287                 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
   2288                 out.attribute(null, "name", component);
   2289                 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
   2290             }
   2291 
   2292             if (policy.mStatusBarDisabled) {
   2293                 out.startTag(null, TAG_STATUS_BAR);
   2294                 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
   2295                 out.endTag(null, TAG_STATUS_BAR);
   2296             }
   2297 
   2298             if (policy.doNotAskCredentialsOnBoot) {
   2299                 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
   2300                 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
   2301             }
   2302 
   2303             for (String id : policy.mAffiliationIds) {
   2304                 out.startTag(null, TAG_AFFILIATION_ID);
   2305                 out.attribute(null, "id", id);
   2306                 out.endTag(null, TAG_AFFILIATION_ID);
   2307             }
   2308 
   2309             if (policy.mAdminBroadcastPending) {
   2310                 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
   2311                 out.attribute(null, ATTR_VALUE,
   2312                         Boolean.toString(policy.mAdminBroadcastPending));
   2313                 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
   2314             }
   2315 
   2316             if (policy.mInitBundle != null) {
   2317                 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
   2318                 policy.mInitBundle.saveToXml(out);
   2319                 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
   2320             }
   2321 
   2322             out.endTag(null, "policies");
   2323 
   2324             out.endDocument();
   2325             stream.flush();
   2326             FileUtils.sync(stream);
   2327             stream.close();
   2328             journal.commit();
   2329             sendChangedNotification(userHandle);
   2330         } catch (XmlPullParserException | IOException e) {
   2331             Slog.w(LOG_TAG, "failed writing file", e);
   2332             try {
   2333                 if (stream != null) {
   2334                     stream.close();
   2335                 }
   2336             } catch (IOException ex) {
   2337                 // Ignore
   2338             }
   2339             journal.rollback();
   2340         }
   2341     }
   2342 
   2343     private void sendChangedNotification(int userHandle) {
   2344         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
   2345         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
   2346         long ident = mInjector.binderClearCallingIdentity();
   2347         try {
   2348             mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
   2349         } finally {
   2350             mInjector.binderRestoreCallingIdentity(ident);
   2351         }
   2352     }
   2353 
   2354     private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
   2355         JournaledFile journal = makeJournaledFile(userHandle);
   2356         FileInputStream stream = null;
   2357         File file = journal.chooseForRead();
   2358         try {
   2359             stream = new FileInputStream(file);
   2360             XmlPullParser parser = Xml.newPullParser();
   2361             parser.setInput(stream, StandardCharsets.UTF_8.name());
   2362 
   2363             int type;
   2364             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
   2365                     && type != XmlPullParser.START_TAG) {
   2366             }
   2367             String tag = parser.getName();
   2368             if (!"policies".equals(tag)) {
   2369                 throw new XmlPullParserException(
   2370                         "Settings do not start with policies tag: found " + tag);
   2371             }
   2372 
   2373             // Extract the permission provider component name if available
   2374             String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
   2375             if (permissionProvider != null) {
   2376                 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
   2377             }
   2378             String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
   2379             if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
   2380                 policy.mUserSetupComplete = true;
   2381             }
   2382             String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
   2383                     ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
   2384             if (deviceProvisioningConfigApplied != null
   2385                     && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
   2386                 policy.mDeviceProvisioningConfigApplied = true;
   2387             }
   2388             String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
   2389             if (!TextUtils.isEmpty(provisioningState)) {
   2390                 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
   2391             }
   2392             String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
   2393             if (!TextUtils.isEmpty(permissionPolicy)) {
   2394                 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
   2395             }
   2396             policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
   2397                     ATTR_DELEGATED_CERT_INSTALLER);
   2398             policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
   2399                     ATTR_APPLICATION_RESTRICTIONS_MANAGER);
   2400 
   2401             type = parser.next();
   2402             int outerDepth = parser.getDepth();
   2403             policy.mLockTaskPackages.clear();
   2404             policy.mAdminList.clear();
   2405             policy.mAdminMap.clear();
   2406             policy.mAffiliationIds.clear();
   2407             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
   2408                    && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   2409                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   2410                     continue;
   2411                 }
   2412                 tag = parser.getName();
   2413                 if ("admin".equals(tag)) {
   2414                     String name = parser.getAttributeValue(null, "name");
   2415                     try {
   2416                         DeviceAdminInfo dai = findAdmin(
   2417                                 ComponentName.unflattenFromString(name), userHandle,
   2418                                 /* throwForMissionPermission= */ false);
   2419                         if (VERBOSE_LOG
   2420                                 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
   2421                                 != userHandle)) {
   2422                             Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
   2423                                     + dai.getActivityInfo().applicationInfo.uid + " for user "
   2424                                     + userHandle);
   2425                         }
   2426                         if (dai != null) {
   2427                             ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
   2428                             ap.readFromXml(parser);
   2429                             policy.mAdminMap.put(ap.info.getComponent(), ap);
   2430                         }
   2431                     } catch (RuntimeException e) {
   2432                         Slog.w(LOG_TAG, "Failed loading admin " + name, e);
   2433                     }
   2434                 } else if ("failed-password-attempts".equals(tag)) {
   2435                     policy.mFailedPasswordAttempts = Integer.parseInt(
   2436                             parser.getAttributeValue(null, "value"));
   2437                 } else if ("password-owner".equals(tag)) {
   2438                     policy.mPasswordOwner = Integer.parseInt(
   2439                             parser.getAttributeValue(null, "value"));
   2440                 } else if ("active-password".equals(tag)) {
   2441                     policy.mActivePasswordQuality = Integer.parseInt(
   2442                             parser.getAttributeValue(null, "quality"));
   2443                     policy.mActivePasswordLength = Integer.parseInt(
   2444                             parser.getAttributeValue(null, "length"));
   2445                     policy.mActivePasswordUpperCase = Integer.parseInt(
   2446                             parser.getAttributeValue(null, "uppercase"));
   2447                     policy.mActivePasswordLowerCase = Integer.parseInt(
   2448                             parser.getAttributeValue(null, "lowercase"));
   2449                     policy.mActivePasswordLetters = Integer.parseInt(
   2450                             parser.getAttributeValue(null, "letters"));
   2451                     policy.mActivePasswordNumeric = Integer.parseInt(
   2452                             parser.getAttributeValue(null, "numeric"));
   2453                     policy.mActivePasswordSymbols = Integer.parseInt(
   2454                             parser.getAttributeValue(null, "symbols"));
   2455                     policy.mActivePasswordNonLetter = Integer.parseInt(
   2456                             parser.getAttributeValue(null, "nonletter"));
   2457                 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
   2458                     policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
   2459                 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
   2460                     policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
   2461                 } else if (TAG_STATUS_BAR.equals(tag)) {
   2462                     policy.mStatusBarDisabled = Boolean.parseBoolean(
   2463                             parser.getAttributeValue(null, ATTR_DISABLED));
   2464                 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
   2465                     policy.doNotAskCredentialsOnBoot = true;
   2466                 } else if (TAG_AFFILIATION_ID.equals(tag)) {
   2467                     policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
   2468                 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
   2469                     String pending = parser.getAttributeValue(null, ATTR_VALUE);
   2470                     policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
   2471                 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
   2472                     policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
   2473                 } else {
   2474                     Slog.w(LOG_TAG, "Unknown tag: " + tag);
   2475                     XmlUtils.skipCurrentTag(parser);
   2476                 }
   2477             }
   2478         } catch (FileNotFoundException e) {
   2479             // Don't be noisy, this is normal if we haven't defined any policies.
   2480         } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
   2481                 | IndexOutOfBoundsException e) {
   2482             Slog.w(LOG_TAG, "failed parsing " + file, e);
   2483         }
   2484         try {
   2485             if (stream != null) {
   2486                 stream.close();
   2487             }
   2488         } catch (IOException e) {
   2489             // Ignore
   2490         }
   2491 
   2492         // Generate a list of admins from the admin map
   2493         policy.mAdminList.addAll(policy.mAdminMap.values());
   2494 
   2495         // Validate that what we stored for the password quality matches
   2496         // sufficiently what is currently set.  Note that this is only
   2497         // a sanity check in case the two get out of sync; this should
   2498         // never normally happen.
   2499         final long identity = mInjector.binderClearCallingIdentity();
   2500         try {
   2501             int actualPasswordQuality = mLockPatternUtils.getActivePasswordQuality(userHandle);
   2502             if (actualPasswordQuality < policy.mActivePasswordQuality) {
   2503                 Slog.w(LOG_TAG, "Active password quality 0x"
   2504                         + Integer.toHexString(policy.mActivePasswordQuality)
   2505                         + " does not match actual quality 0x"
   2506                         + Integer.toHexString(actualPasswordQuality));
   2507                 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
   2508                 policy.mActivePasswordLength = 0;
   2509                 policy.mActivePasswordUpperCase = 0;
   2510                 policy.mActivePasswordLowerCase = 0;
   2511                 policy.mActivePasswordLetters = 0;
   2512                 policy.mActivePasswordNumeric = 0;
   2513                 policy.mActivePasswordSymbols = 0;
   2514                 policy.mActivePasswordNonLetter = 0;
   2515             }
   2516         } finally {
   2517             mInjector.binderRestoreCallingIdentity(identity);
   2518         }
   2519 
   2520         validatePasswordOwnerLocked(policy);
   2521         updateMaximumTimeToLockLocked(userHandle);
   2522         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
   2523         if (policy.mStatusBarDisabled) {
   2524             setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
   2525         }
   2526     }
   2527 
   2528     private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
   2529         long ident = mInjector.binderClearCallingIdentity();
   2530         try {
   2531             mInjector.getIActivityManager()
   2532                     .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
   2533         } catch (RemoteException e) {
   2534             // Not gonna happen.
   2535         } finally {
   2536             mInjector.binderRestoreCallingIdentity(ident);
   2537         }
   2538     }
   2539 
   2540     private void updateDeviceOwnerLocked() {
   2541         long ident = mInjector.binderClearCallingIdentity();
   2542         try {
   2543             // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
   2544             // user id and also protect all other DAs too.
   2545             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
   2546             if (deviceOwnerComponent != null) {
   2547                 mInjector.getIActivityManager()
   2548                         .updateDeviceOwner(deviceOwnerComponent.getPackageName());
   2549             }
   2550         } catch (RemoteException e) {
   2551             // Not gonna happen.
   2552         } finally {
   2553             mInjector.binderRestoreCallingIdentity(ident);
   2554         }
   2555     }
   2556 
   2557     static void validateQualityConstant(int quality) {
   2558         switch (quality) {
   2559             case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
   2560             case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
   2561             case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
   2562             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
   2563             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
   2564             case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
   2565             case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
   2566             case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
   2567             case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
   2568                 return;
   2569         }
   2570         throw new IllegalArgumentException("Invalid quality constant: 0x"
   2571                 + Integer.toHexString(quality));
   2572     }
   2573 
   2574     void validatePasswordOwnerLocked(DevicePolicyData policy) {
   2575         if (policy.mPasswordOwner >= 0) {
   2576             boolean haveOwner = false;
   2577             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
   2578                 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
   2579                     haveOwner = true;
   2580                     break;
   2581                 }
   2582             }
   2583             if (!haveOwner) {
   2584                 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
   2585                         + " no longer active; disabling");
   2586                 policy.mPasswordOwner = -1;
   2587             }
   2588         }
   2589     }
   2590 
   2591     @VisibleForTesting
   2592     void systemReady(int phase) {
   2593         if (!mHasFeature) {
   2594             return;
   2595         }
   2596         switch (phase) {
   2597             case SystemService.PHASE_LOCK_SETTINGS_READY:
   2598                 onLockSettingsReady();
   2599                 break;
   2600             case SystemService.PHASE_BOOT_COMPLETED:
   2601                 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
   2602                 break;
   2603         }
   2604     }
   2605 
   2606     private void onLockSettingsReady() {
   2607         getUserData(UserHandle.USER_SYSTEM);
   2608         loadOwners();
   2609         cleanUpOldUsers();
   2610 
   2611         onStartUser(UserHandle.USER_SYSTEM);
   2612 
   2613         // Register an observer for watching for user setup complete.
   2614         new SetupContentObserver(mHandler).register();
   2615         // Initialize the user setup state, to handle the upgrade case.
   2616         updateUserSetupComplete();
   2617 
   2618         List<String> packageList;
   2619         synchronized (this) {
   2620             packageList = getKeepUninstalledPackagesLocked();
   2621         }
   2622         if (packageList != null) {
   2623             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
   2624         }
   2625 
   2626         synchronized (this) {
   2627             // push the force-ephemeral-users policy to the user manager.
   2628             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
   2629             if (deviceOwner != null) {
   2630                 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
   2631             }
   2632         }
   2633     }
   2634 
   2635     private void ensureDeviceOwnerUserStarted() {
   2636         final int userId;
   2637         synchronized (this) {
   2638             if (!mOwners.hasDeviceOwner()) {
   2639                 return;
   2640             }
   2641             userId = mOwners.getDeviceOwnerUserId();
   2642         }
   2643         if (VERBOSE_LOG) {
   2644             Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
   2645         }
   2646         if (userId != UserHandle.USER_SYSTEM) {
   2647             try {
   2648                 mInjector.getIActivityManager().startUserInBackground(userId);
   2649 
   2650                 // STOPSHIP Prevent the DO user from being killed.
   2651 
   2652             } catch (RemoteException e) {
   2653                 Slog.w(LOG_TAG, "Exception starting user", e);
   2654             }
   2655         }
   2656     }
   2657 
   2658     private void onStartUser(int userId) {
   2659         updateScreenCaptureDisabledInWindowManager(userId,
   2660                 getScreenCaptureDisabled(null, userId));
   2661         pushUserRestrictions(userId);
   2662     }
   2663 
   2664     private void cleanUpOldUsers() {
   2665         // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
   2666         // before reboot
   2667         Set<Integer> usersWithProfileOwners;
   2668         Set<Integer> usersWithData;
   2669         synchronized(this) {
   2670             usersWithProfileOwners = mOwners.getProfileOwnerKeys();
   2671             usersWithData = new ArraySet<>();
   2672             for (int i = 0; i < mUserData.size(); i++) {
   2673                 usersWithData.add(mUserData.keyAt(i));
   2674             }
   2675         }
   2676         List<UserInfo> allUsers = mUserManager.getUsers();
   2677 
   2678         Set<Integer> deletedUsers = new ArraySet<>();
   2679         deletedUsers.addAll(usersWithProfileOwners);
   2680         deletedUsers.addAll(usersWithData);
   2681         for (UserInfo userInfo : allUsers) {
   2682             deletedUsers.remove(userInfo.id);
   2683         }
   2684         for (Integer userId : deletedUsers) {
   2685             removeUserData(userId);
   2686         }
   2687     }
   2688 
   2689     private void handlePasswordExpirationNotification(int userHandle) {
   2690         synchronized (this) {
   2691             final long now = System.currentTimeMillis();
   2692 
   2693             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
   2694                     userHandle, /* parent */ false);
   2695             final int N = admins.size();
   2696             for (int i = 0; i < N; i++) {
   2697                 ActiveAdmin admin = admins.get(i);
   2698                 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
   2699                         && admin.passwordExpirationTimeout > 0L
   2700                         && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
   2701                         && admin.passwordExpirationDate > 0L) {
   2702                     sendAdminCommandLocked(admin,
   2703                             DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
   2704                 }
   2705             }
   2706             setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
   2707         }
   2708     }
   2709 
   2710     private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
   2711         @Override
   2712         protected Void doInBackground(Integer... params) {
   2713             int userHandle = params[0];
   2714 
   2715             if (userHandle == UserHandle.USER_ALL) {
   2716                 for (UserInfo userInfo : mUserManager.getUsers(true)) {
   2717                     manageNotification(userInfo.getUserHandle());
   2718                 }
   2719             } else {
   2720                 manageNotification(UserHandle.of(userHandle));
   2721             }
   2722             return null;
   2723         }
   2724 
   2725         private void manageNotification(UserHandle userHandle) {
   2726             if (!mUserManager.isUserUnlocked(userHandle)) {
   2727                 return;
   2728             }
   2729 
   2730             // Call out to KeyChain to check for CAs which are waiting for approval.
   2731             final List<String> pendingCertificates;
   2732             try {
   2733                 pendingCertificates = getInstalledCaCertificates(userHandle);
   2734             } catch (RemoteException | RuntimeException e) {
   2735                 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
   2736                 return;
   2737             }
   2738 
   2739             synchronized (DevicePolicyManagerService.this) {
   2740                 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
   2741 
   2742                 // Remove deleted certificates. Flush xml if necessary.
   2743                 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
   2744                     saveSettingsLocked(userHandle.getIdentifier());
   2745                 }
   2746                 // Trim to approved certificates.
   2747                 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
   2748             }
   2749 
   2750             if (pendingCertificates.isEmpty()) {
   2751                 mInjector.getNotificationManager().cancelAsUser(
   2752                         null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
   2753                 return;
   2754             }
   2755 
   2756             // Build and show a warning notification
   2757             int smallIconId;
   2758             String contentText;
   2759             int parentUserId = userHandle.getIdentifier();
   2760             if (getProfileOwner(userHandle.getIdentifier()) != null) {
   2761                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
   2762                         getProfileOwnerName(userHandle.getIdentifier()));
   2763                 smallIconId = R.drawable.stat_sys_certificate_info;
   2764                 parentUserId = getProfileParentId(userHandle.getIdentifier());
   2765             } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
   2766                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
   2767                         getDeviceOwnerName());
   2768                 smallIconId = R.drawable.stat_sys_certificate_info;
   2769             } else {
   2770                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
   2771                 smallIconId = android.R.drawable.stat_sys_warning;
   2772             }
   2773 
   2774             final int numberOfCertificates = pendingCertificates.size();
   2775             Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
   2776             dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
   2777             dialogIntent.setPackage("com.android.settings");
   2778             dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
   2779             dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
   2780             PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
   2781                     dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
   2782                     new UserHandle(parentUserId));
   2783 
   2784             final Context userContext;
   2785             try {
   2786                 final String packageName = mContext.getPackageName();
   2787                 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
   2788             } catch (PackageManager.NameNotFoundException e) {
   2789                 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
   2790                 return;
   2791             }
   2792             final Notification noti = new Notification.Builder(userContext)
   2793                 .setSmallIcon(smallIconId)
   2794                 .setContentTitle(mContext.getResources().getQuantityText(
   2795                         R.plurals.ssl_ca_cert_warning, numberOfCertificates))
   2796                 .setContentText(contentText)
   2797                 .setContentIntent(notifyIntent)
   2798                 .setPriority(Notification.PRIORITY_HIGH)
   2799                 .setShowWhen(false)
   2800                 .setColor(mContext.getColor(
   2801                         com.android.internal.R.color.system_notification_accent_color))
   2802                 .build();
   2803 
   2804             mInjector.getNotificationManager().notifyAsUser(
   2805                     null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
   2806         }
   2807 
   2808         private List<String> getInstalledCaCertificates(UserHandle userHandle)
   2809                 throws RemoteException, RuntimeException {
   2810             KeyChainConnection conn = null;
   2811             try {
   2812                 conn = KeyChain.bindAsUser(mContext, userHandle);
   2813                 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
   2814                 List<String> result = new ArrayList<>(aliases.size());
   2815                 for (int i = 0; i < aliases.size(); i++) {
   2816                     result.add(aliases.get(i).string);
   2817                 }
   2818                 return result;
   2819             } catch (InterruptedException e) {
   2820                 Thread.currentThread().interrupt();
   2821                 return null;
   2822             } catch (AssertionError e) {
   2823                 throw new RuntimeException(e);
   2824             } finally {
   2825                 if (conn != null) {
   2826                     conn.close();
   2827                 }
   2828             }
   2829         }
   2830     }
   2831 
   2832     /**
   2833      * @param adminReceiver The admin to add
   2834      * @param refreshing true = update an active admin, no error
   2835      */
   2836     @Override
   2837     public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
   2838         if (!mHasFeature) {
   2839             return;
   2840         }
   2841         setActiveAdmin(adminReceiver, refreshing, userHandle, null);
   2842     }
   2843 
   2844     private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
   2845             Bundle onEnableData) {
   2846         mContext.enforceCallingOrSelfPermission(
   2847                 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
   2848         enforceFullCrossUsersPermission(userHandle);
   2849 
   2850         DevicePolicyData policy = getUserData(userHandle);
   2851         DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
   2852                 /* throwForMissionPermission= */ true);
   2853         if (info == null) {
   2854             throw new IllegalArgumentException("Bad admin: " + adminReceiver);
   2855         }
   2856         if (!info.getActivityInfo().applicationInfo.isInternal()) {
   2857             throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
   2858                     + adminReceiver);
   2859         }
   2860         synchronized (this) {
   2861             long ident = mInjector.binderClearCallingIdentity();
   2862             try {
   2863                 final ActiveAdmin existingAdmin
   2864                         = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
   2865                 if (!refreshing && existingAdmin != null) {
   2866                     throw new IllegalArgumentException("Admin is already added");
   2867                 }
   2868                 if (policy.mRemovingAdmins.contains(adminReceiver)) {
   2869                     throw new IllegalArgumentException(
   2870                             "Trying to set an admin which is being removed");
   2871                 }
   2872                 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
   2873                 newAdmin.testOnlyAdmin =
   2874                         (existingAdmin != null) ? existingAdmin.testOnlyAdmin
   2875                                 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
   2876                 policy.mAdminMap.put(adminReceiver, newAdmin);
   2877                 int replaceIndex = -1;
   2878                 final int N = policy.mAdminList.size();
   2879                 for (int i=0; i < N; i++) {
   2880                     ActiveAdmin oldAdmin = policy.mAdminList.get(i);
   2881                     if (oldAdmin.info.getComponent().equals(adminReceiver)) {
   2882                         replaceIndex = i;
   2883                         break;
   2884                     }
   2885                 }
   2886                 if (replaceIndex == -1) {
   2887                     policy.mAdminList.add(newAdmin);
   2888                     enableIfNecessary(info.getPackageName(), userHandle);
   2889                 } else {
   2890                     policy.mAdminList.set(replaceIndex, newAdmin);
   2891                 }
   2892                 saveSettingsLocked(userHandle);
   2893                 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
   2894                         onEnableData, null);
   2895             } finally {
   2896                 mInjector.binderRestoreCallingIdentity(ident);
   2897             }
   2898         }
   2899     }
   2900 
   2901     @Override
   2902     public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
   2903         if (!mHasFeature) {
   2904             return false;
   2905         }
   2906         enforceFullCrossUsersPermission(userHandle);
   2907         synchronized (this) {
   2908             return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
   2909         }
   2910     }
   2911 
   2912     @Override
   2913     public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
   2914         if (!mHasFeature) {
   2915             return false;
   2916         }
   2917         enforceFullCrossUsersPermission(userHandle);
   2918         synchronized (this) {
   2919             DevicePolicyData policyData = getUserData(userHandle);
   2920             return policyData.mRemovingAdmins.contains(adminReceiver);
   2921         }
   2922     }
   2923 
   2924     @Override
   2925     public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
   2926         if (!mHasFeature) {
   2927             return false;
   2928         }
   2929         enforceFullCrossUsersPermission(userHandle);
   2930         synchronized (this) {
   2931             ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
   2932             if (administrator == null) {
   2933                 throw new SecurityException("No active admin " + adminReceiver);
   2934             }
   2935             return administrator.info.usesPolicy(policyId);
   2936         }
   2937     }
   2938 
   2939     @Override
   2940     @SuppressWarnings("unchecked")
   2941     public List<ComponentName> getActiveAdmins(int userHandle) {
   2942         if (!mHasFeature) {
   2943             return Collections.EMPTY_LIST;
   2944         }
   2945 
   2946         enforceFullCrossUsersPermission(userHandle);
   2947         synchronized (this) {
   2948             DevicePolicyData policy = getUserData(userHandle);
   2949             final int N = policy.mAdminList.size();
   2950             if (N <= 0) {
   2951                 return null;
   2952             }
   2953             ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
   2954             for (int i=0; i<N; i++) {
   2955                 res.add(policy.mAdminList.get(i).info.getComponent());
   2956             }
   2957             return res;
   2958         }
   2959     }
   2960 
   2961     @Override
   2962     public boolean packageHasActiveAdmins(String packageName, int userHandle) {
   2963         if (!mHasFeature) {
   2964             return false;
   2965         }
   2966         enforceFullCrossUsersPermission(userHandle);
   2967         synchronized (this) {
   2968             DevicePolicyData policy = getUserData(userHandle);
   2969             final int N = policy.mAdminList.size();
   2970             for (int i=0; i<N; i++) {
   2971                 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
   2972                     return true;
   2973                 }
   2974             }
   2975             return false;
   2976         }
   2977     }
   2978 
   2979     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
   2980         if (!mHasFeature) {
   2981             return;
   2982         }
   2983         Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
   2984         enforceShell("forceRemoveActiveAdmin");
   2985         long ident = mInjector.binderClearCallingIdentity();
   2986         try {
   2987             synchronized (this)  {
   2988                 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
   2989                     throw new SecurityException("Attempt to remove non-test admin "
   2990                             + adminReceiver + " " + userHandle);
   2991                 }
   2992 
   2993                 // If admin is a device or profile owner tidy that up first.
   2994                 if (isDeviceOwner(adminReceiver, userHandle)) {
   2995                     clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
   2996                 }
   2997                 if (isProfileOwner(adminReceiver, userHandle)) {
   2998                     final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
   2999                             userHandle, /* parent */ false);
   3000                     clearProfileOwnerLocked(admin, userHandle);
   3001                 }
   3002             }
   3003             // Remove the admin skipping sending the broadcast.
   3004             removeAdminArtifacts(adminReceiver, userHandle);
   3005             Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
   3006         } finally {
   3007             mInjector.binderRestoreCallingIdentity(ident);
   3008         }
   3009     }
   3010 
   3011     /**
   3012      * Return if a given package has testOnly="true", in which case we'll relax certain rules
   3013      * for CTS.
   3014      *
   3015      * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
   3016      * to check wehter an active admin is test-only or not.
   3017      *
   3018      * The system allows this flag to be changed when an app is updated, which is not good
   3019      * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
   3020      * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
   3021      */
   3022     private boolean isPackageTestOnly(String packageName, int userHandle) {
   3023         final ApplicationInfo ai;
   3024         try {
   3025             ai = mIPackageManager.getApplicationInfo(packageName,
   3026                     (PackageManager.MATCH_DIRECT_BOOT_AWARE
   3027                             | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
   3028         } catch (RemoteException e) {
   3029             throw new IllegalStateException(e);
   3030         }
   3031         if (ai == null) {
   3032             throw new IllegalStateException("Couldn't find package: "
   3033                     + packageName + " on user " + userHandle);
   3034         }
   3035         return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
   3036     }
   3037 
   3038     /**
   3039      * See {@link #isPackageTestOnly}.
   3040      */
   3041     private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
   3042         final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   3043         return (admin != null) && admin.testOnlyAdmin;
   3044     }
   3045 
   3046     private void enforceShell(String method) {
   3047         final int callingUid = Binder.getCallingUid();
   3048         if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
   3049             throw new SecurityException("Non-shell user attempted to call " + method);
   3050         }
   3051     }
   3052 
   3053     @Override
   3054     public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
   3055         if (!mHasFeature) {
   3056             return;
   3057         }
   3058         enforceFullCrossUsersPermission(userHandle);
   3059         enforceUserUnlocked(userHandle);
   3060         synchronized (this) {
   3061             ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
   3062             if (admin == null) {
   3063                 return;
   3064             }
   3065             // Active device/profile owners must remain active admins.
   3066             if (isDeviceOwner(adminReceiver, userHandle)
   3067                     || isProfileOwner(adminReceiver, userHandle)) {
   3068                 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
   3069                         adminReceiver);
   3070                 return;
   3071             }
   3072             if (admin.getUid() != mInjector.binderGetCallingUid()) {
   3073                 mContext.enforceCallingOrSelfPermission(
   3074                         android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
   3075             }
   3076             long ident = mInjector.binderClearCallingIdentity();
   3077             try {
   3078                 removeActiveAdminLocked(adminReceiver, userHandle);
   3079             } finally {
   3080                 mInjector.binderRestoreCallingIdentity(ident);
   3081             }
   3082         }
   3083     }
   3084 
   3085     @Override
   3086     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
   3087         ComponentName profileOwner = getProfileOwner(userHandle);
   3088         // Profile challenge is supported on N or newer release.
   3089         return profileOwner != null &&
   3090                 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
   3091     }
   3092 
   3093     @Override
   3094     public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
   3095         if (!mHasFeature) {
   3096             return;
   3097         }
   3098         Preconditions.checkNotNull(who, "ComponentName is null");
   3099         validateQualityConstant(quality);
   3100 
   3101         synchronized (this) {
   3102             ActiveAdmin ap = getActiveAdminForCallerLocked(
   3103                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
   3104             if (ap.passwordQuality != quality) {
   3105                 ap.passwordQuality = quality;
   3106                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   3107             }
   3108         }
   3109     }
   3110 
   3111     @Override
   3112     public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
   3113         if (!mHasFeature) {
   3114             return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
   3115         }
   3116         enforceFullCrossUsersPermission(userHandle);
   3117         synchronized (this) {
   3118             int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
   3119 
   3120             if (who != null) {
   3121                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   3122                 return admin != null ? admin.passwordQuality : mode;
   3123             }
   3124 
   3125             // Return the strictest policy across all participating admins.
   3126             List<ActiveAdmin> admins =
   3127                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3128             final int N = admins.size();
   3129             for (int i = 0; i < N; i++) {
   3130                 ActiveAdmin admin = admins.get(i);
   3131                 if (mode < admin.passwordQuality) {
   3132                     mode = admin.passwordQuality;
   3133                 }
   3134             }
   3135             return mode;
   3136         }
   3137     }
   3138 
   3139     private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
   3140             int userHandle, boolean parent) {
   3141         if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
   3142             // If this user has a separate challenge, only return its restrictions.
   3143             return getUserDataUnchecked(userHandle).mAdminList;
   3144         } else {
   3145             // Return all admins for this user and the profiles that are visible from this
   3146             // user that do not use a separate work challenge.
   3147             ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
   3148             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
   3149                 DevicePolicyData policy = getUserData(userInfo.id);
   3150                 if (!userInfo.isManagedProfile()) {
   3151                     admins.addAll(policy.mAdminList);
   3152                 } else {
   3153                     // For managed profiles, we always include the policies set on the parent
   3154                     // profile. Additionally, we include the ones set on the managed profile
   3155                     // if no separate challenge is in place.
   3156                     boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
   3157                     final int N = policy.mAdminList.size();
   3158                     for (int i = 0; i < N; i++) {
   3159                         ActiveAdmin admin = policy.mAdminList.get(i);
   3160                         if (admin.hasParentActiveAdmin()) {
   3161                             admins.add(admin.getParentActiveAdmin());
   3162                         }
   3163                         if (!hasSeparateChallenge) {
   3164                             admins.add(admin);
   3165                         }
   3166                     }
   3167                 }
   3168             }
   3169             return admins;
   3170         }
   3171     }
   3172 
   3173     private boolean isSeparateProfileChallengeEnabled(int userHandle) {
   3174         long ident = mInjector.binderClearCallingIdentity();
   3175         try {
   3176             return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
   3177         } finally {
   3178             mInjector.binderRestoreCallingIdentity(ident);
   3179         }
   3180     }
   3181 
   3182     @Override
   3183     public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
   3184         if (!mHasFeature) {
   3185             return;
   3186         }
   3187         Preconditions.checkNotNull(who, "ComponentName is null");
   3188         synchronized (this) {
   3189             ActiveAdmin ap = getActiveAdminForCallerLocked(
   3190                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
   3191             if (ap.minimumPasswordLength != length) {
   3192                 ap.minimumPasswordLength = length;
   3193                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   3194             }
   3195         }
   3196     }
   3197 
   3198     @Override
   3199     public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
   3200         if (!mHasFeature) {
   3201             return 0;
   3202         }
   3203         enforceFullCrossUsersPermission(userHandle);
   3204         synchronized (this) {
   3205             int length = 0;
   3206 
   3207             if (who != null) {
   3208                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   3209                 return admin != null ? admin.minimumPasswordLength : length;
   3210             }
   3211 
   3212             // Return the strictest policy across all participating admins.
   3213             List<ActiveAdmin> admins =
   3214                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3215             final int N = admins.size();
   3216             for (int i = 0; i < N; i++) {
   3217                 ActiveAdmin admin = admins.get(i);
   3218                 if (length < admin.minimumPasswordLength) {
   3219                     length = admin.minimumPasswordLength;
   3220                 }
   3221             }
   3222             return length;
   3223         }
   3224     }
   3225 
   3226     @Override
   3227     public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
   3228         if (!mHasFeature) {
   3229             return;
   3230         }
   3231         Preconditions.checkNotNull(who, "ComponentName is null");
   3232         synchronized (this) {
   3233             ActiveAdmin ap = getActiveAdminForCallerLocked(
   3234                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
   3235             if (ap.passwordHistoryLength != length) {
   3236                 ap.passwordHistoryLength = length;
   3237                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   3238             }
   3239         }
   3240     }
   3241 
   3242     @Override
   3243     public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
   3244         if (!mHasFeature) {
   3245             return 0;
   3246         }
   3247         enforceFullCrossUsersPermission(userHandle);
   3248         synchronized (this) {
   3249             int length = 0;
   3250 
   3251             if (who != null) {
   3252                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   3253                 return admin != null ? admin.passwordHistoryLength : length;
   3254             }
   3255 
   3256             // Return the strictest policy across all participating admins.
   3257             List<ActiveAdmin> admins =
   3258                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3259             final int N = admins.size();
   3260             for (int i = 0; i < N; i++) {
   3261                 ActiveAdmin admin = admins.get(i);
   3262                 if (length < admin.passwordHistoryLength) {
   3263                     length = admin.passwordHistoryLength;
   3264                 }
   3265             }
   3266 
   3267             return length;
   3268         }
   3269     }
   3270 
   3271     @Override
   3272     public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
   3273         if (!mHasFeature) {
   3274             return;
   3275         }
   3276         Preconditions.checkNotNull(who, "ComponentName is null");
   3277         Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
   3278         final int userHandle = mInjector.userHandleGetCallingUserId();
   3279         synchronized (this) {
   3280             ActiveAdmin ap = getActiveAdminForCallerLocked(
   3281                     who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
   3282             // Calling this API automatically bumps the expiration date
   3283             final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
   3284             ap.passwordExpirationDate = expiration;
   3285             ap.passwordExpirationTimeout = timeout;
   3286             if (timeout > 0L) {
   3287                 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
   3288                         + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
   3289                         .format(new Date(expiration)));
   3290             }
   3291             saveSettingsLocked(userHandle);
   3292 
   3293             // in case this is the first one, set the alarm on the appropriate user.
   3294             setExpirationAlarmCheckLocked(mContext, userHandle, parent);
   3295         }
   3296     }
   3297 
   3298     /**
   3299      * Return a single admin's expiration cycle time, or the min of all cycle times.
   3300      * Returns 0 if not configured.
   3301      */
   3302     @Override
   3303     public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
   3304         if (!mHasFeature) {
   3305             return 0L;
   3306         }
   3307         enforceFullCrossUsersPermission(userHandle);
   3308         synchronized (this) {
   3309             long timeout = 0L;
   3310 
   3311             if (who != null) {
   3312                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   3313                 return admin != null ? admin.passwordExpirationTimeout : timeout;
   3314             }
   3315 
   3316             // Return the strictest policy across all participating admins.
   3317             List<ActiveAdmin> admins =
   3318                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3319             final int N = admins.size();
   3320             for (int i = 0; i < N; i++) {
   3321                 ActiveAdmin admin = admins.get(i);
   3322                 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
   3323                         && timeout > admin.passwordExpirationTimeout)) {
   3324                     timeout = admin.passwordExpirationTimeout;
   3325                 }
   3326             }
   3327             return timeout;
   3328         }
   3329     }
   3330 
   3331     @Override
   3332     public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
   3333         final int userId = UserHandle.getCallingUserId();
   3334         List<String> changedProviders = null;
   3335 
   3336         synchronized (this) {
   3337             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
   3338                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   3339             if (activeAdmin.crossProfileWidgetProviders == null) {
   3340                 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
   3341             }
   3342             List<String> providers = activeAdmin.crossProfileWidgetProviders;
   3343             if (!providers.contains(packageName)) {
   3344                 providers.add(packageName);
   3345                 changedProviders = new ArrayList<>(providers);
   3346                 saveSettingsLocked(userId);
   3347             }
   3348         }
   3349 
   3350         if (changedProviders != null) {
   3351             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
   3352             return true;
   3353         }
   3354 
   3355         return false;
   3356     }
   3357 
   3358     @Override
   3359     public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
   3360         final int userId = UserHandle.getCallingUserId();
   3361         List<String> changedProviders = null;
   3362 
   3363         synchronized (this) {
   3364             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
   3365                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   3366             if (activeAdmin.crossProfileWidgetProviders == null) {
   3367                 return false;
   3368             }
   3369             List<String> providers = activeAdmin.crossProfileWidgetProviders;
   3370             if (providers.remove(packageName)) {
   3371                 changedProviders = new ArrayList<>(providers);
   3372                 saveSettingsLocked(userId);
   3373             }
   3374         }
   3375 
   3376         if (changedProviders != null) {
   3377             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
   3378             return true;
   3379         }
   3380 
   3381         return false;
   3382     }
   3383 
   3384     @Override
   3385     public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
   3386         synchronized (this) {
   3387             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
   3388                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   3389             if (activeAdmin.crossProfileWidgetProviders == null
   3390                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
   3391                 return null;
   3392             }
   3393             if (mInjector.binderIsCallingUidMyUid()) {
   3394                 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
   3395             } else {
   3396                 return activeAdmin.crossProfileWidgetProviders;
   3397             }
   3398         }
   3399     }
   3400 
   3401     /**
   3402      * Return a single admin's expiration date/time, or the min (soonest) for all admins.
   3403      * Returns 0 if not configured.
   3404      */
   3405     private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
   3406         long timeout = 0L;
   3407 
   3408         if (who != null) {
   3409             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   3410             return admin != null ? admin.passwordExpirationDate : timeout;
   3411         }
   3412 
   3413         // Return the strictest policy across all participating admins.
   3414         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3415         final int N = admins.size();
   3416         for (int i = 0; i < N; i++) {
   3417             ActiveAdmin admin = admins.get(i);
   3418             if (timeout == 0L || (admin.passwordExpirationDate != 0
   3419                     && timeout > admin.passwordExpirationDate)) {
   3420                 timeout = admin.passwordExpirationDate;
   3421             }
   3422         }
   3423         return timeout;
   3424     }
   3425 
   3426     @Override
   3427     public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
   3428         if (!mHasFeature) {
   3429             return 0L;
   3430         }
   3431         enforceFullCrossUsersPermission(userHandle);
   3432         synchronized (this) {
   3433             return getPasswordExpirationLocked(who, userHandle, parent);
   3434         }
   3435     }
   3436 
   3437     @Override
   3438     public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
   3439         if (!mHasFeature) {
   3440             return;
   3441         }
   3442         Preconditions.checkNotNull(who, "ComponentName is null");
   3443         synchronized (this) {
   3444             ActiveAdmin ap = getActiveAdminForCallerLocked(
   3445                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
   3446             if (ap.minimumPasswordUpperCase != length) {
   3447                 ap.minimumPasswordUpperCase = length;
   3448                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   3449             }
   3450         }
   3451     }
   3452 
   3453     @Override
   3454     public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
   3455         if (!mHasFeature) {
   3456             return 0;
   3457         }
   3458         enforceFullCrossUsersPermission(userHandle);
   3459         synchronized (this) {
   3460             int length = 0;
   3461 
   3462             if (who != null) {
   3463                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   3464                 return admin != null ? admin.minimumPasswordUpperCase : length;
   3465             }
   3466 
   3467             // Return the strictest policy across all participating admins.
   3468             List<ActiveAdmin> admins =
   3469                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3470             final int N = admins.size();
   3471             for (int i = 0; i < N; i++) {
   3472                 ActiveAdmin admin = admins.get(i);
   3473                 if (length < admin.minimumPasswordUpperCase) {
   3474                     length = admin.minimumPasswordUpperCase;
   3475                 }
   3476             }
   3477             return length;
   3478         }
   3479     }
   3480 
   3481     @Override
   3482     public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
   3483         Preconditions.checkNotNull(who, "ComponentName is null");
   3484         synchronized (this) {
   3485             ActiveAdmin ap = getActiveAdminForCallerLocked(
   3486                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
   3487             if (ap.minimumPasswordLowerCase != length) {
   3488                 ap.minimumPasswordLowerCase = length;
   3489                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   3490             }
   3491         }
   3492     }
   3493 
   3494     @Override
   3495     public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
   3496         if (!mHasFeature) {
   3497             return 0;
   3498         }
   3499         enforceFullCrossUsersPermission(userHandle);
   3500         synchronized (this) {
   3501             int length = 0;
   3502 
   3503             if (who != null) {
   3504                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   3505                 return admin != null ? admin.minimumPasswordLowerCase : length;
   3506             }
   3507 
   3508             // Return the strictest policy across all participating admins.
   3509             List<ActiveAdmin> admins =
   3510                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3511             final int N = admins.size();
   3512             for (int i = 0; i < N; i++) {
   3513                 ActiveAdmin admin = admins.get(i);
   3514                 if (length < admin.minimumPasswordLowerCase) {
   3515                     length = admin.minimumPasswordLowerCase;
   3516                 }
   3517             }
   3518             return length;
   3519         }
   3520     }
   3521 
   3522     @Override
   3523     public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
   3524         if (!mHasFeature) {
   3525             return;
   3526         }
   3527         Preconditions.checkNotNull(who, "ComponentName is null");
   3528         synchronized (this) {
   3529             ActiveAdmin ap = getActiveAdminForCallerLocked(
   3530                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
   3531             if (ap.minimumPasswordLetters != length) {
   3532                 ap.minimumPasswordLetters = length;
   3533                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   3534             }
   3535         }
   3536     }
   3537 
   3538     @Override
   3539     public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
   3540         if (!mHasFeature) {
   3541             return 0;
   3542         }
   3543         enforceFullCrossUsersPermission(userHandle);
   3544         synchronized (this) {
   3545             int length = 0;
   3546 
   3547             if (who != null) {
   3548                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   3549                 return admin != null ? admin.minimumPasswordLetters : length;
   3550             }
   3551 
   3552             // Return the strictest policy across all participating admins.
   3553             List<ActiveAdmin> admins =
   3554                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3555             final int N = admins.size();
   3556             for (int i = 0; i < N; i++) {
   3557                 ActiveAdmin admin = admins.get(i);
   3558                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
   3559                     continue;
   3560                 }
   3561                 if (length < admin.minimumPasswordLetters) {
   3562                     length = admin.minimumPasswordLetters;
   3563                 }
   3564             }
   3565             return length;
   3566         }
   3567     }
   3568 
   3569     @Override
   3570     public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
   3571         if (!mHasFeature) {
   3572             return;
   3573         }
   3574         Preconditions.checkNotNull(who, "ComponentName is null");
   3575         synchronized (this) {
   3576             ActiveAdmin ap = getActiveAdminForCallerLocked(
   3577                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
   3578             if (ap.minimumPasswordNumeric != length) {
   3579                 ap.minimumPasswordNumeric = length;
   3580                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   3581             }
   3582         }
   3583     }
   3584 
   3585     @Override
   3586     public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
   3587         if (!mHasFeature) {
   3588             return 0;
   3589         }
   3590         enforceFullCrossUsersPermission(userHandle);
   3591         synchronized (this) {
   3592             int length = 0;
   3593 
   3594             if (who != null) {
   3595                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   3596                 return admin != null ? admin.minimumPasswordNumeric : length;
   3597             }
   3598 
   3599             // Return the strictest policy across all participating admins.
   3600             List<ActiveAdmin> admins =
   3601                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3602             final int N = admins.size();
   3603             for (int i = 0; i < N; i++) {
   3604                 ActiveAdmin admin = admins.get(i);
   3605                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
   3606                     continue;
   3607                 }
   3608                 if (length < admin.minimumPasswordNumeric) {
   3609                     length = admin.minimumPasswordNumeric;
   3610                 }
   3611             }
   3612             return length;
   3613         }
   3614     }
   3615 
   3616     @Override
   3617     public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
   3618         if (!mHasFeature) {
   3619             return;
   3620         }
   3621         Preconditions.checkNotNull(who, "ComponentName is null");
   3622         synchronized (this) {
   3623             ActiveAdmin ap = getActiveAdminForCallerLocked(
   3624                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
   3625             if (ap.minimumPasswordSymbols != length) {
   3626                 ap.minimumPasswordSymbols = length;
   3627                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   3628             }
   3629         }
   3630     }
   3631 
   3632     @Override
   3633     public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
   3634         if (!mHasFeature) {
   3635             return 0;
   3636         }
   3637         enforceFullCrossUsersPermission(userHandle);
   3638         synchronized (this) {
   3639             int length = 0;
   3640 
   3641             if (who != null) {
   3642                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   3643                 return admin != null ? admin.minimumPasswordSymbols : length;
   3644             }
   3645 
   3646             // Return the strictest policy across all participating admins.
   3647             List<ActiveAdmin> admins =
   3648                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3649             final int N = admins.size();
   3650             for (int i = 0; i < N; i++) {
   3651                 ActiveAdmin admin = admins.get(i);
   3652                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
   3653                     continue;
   3654                 }
   3655                 if (length < admin.minimumPasswordSymbols) {
   3656                     length = admin.minimumPasswordSymbols;
   3657                 }
   3658             }
   3659             return length;
   3660         }
   3661     }
   3662 
   3663     @Override
   3664     public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
   3665         if (!mHasFeature) {
   3666             return;
   3667         }
   3668         Preconditions.checkNotNull(who, "ComponentName is null");
   3669         synchronized (this) {
   3670             ActiveAdmin ap = getActiveAdminForCallerLocked(
   3671                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
   3672             if (ap.minimumPasswordNonLetter != length) {
   3673                 ap.minimumPasswordNonLetter = length;
   3674                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   3675             }
   3676         }
   3677     }
   3678 
   3679     @Override
   3680     public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
   3681         if (!mHasFeature) {
   3682             return 0;
   3683         }
   3684         enforceFullCrossUsersPermission(userHandle);
   3685         synchronized (this) {
   3686             int length = 0;
   3687 
   3688             if (who != null) {
   3689                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   3690                 return admin != null ? admin.minimumPasswordNonLetter : length;
   3691             }
   3692 
   3693             // Return the strictest policy across all participating admins.
   3694             List<ActiveAdmin> admins =
   3695                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3696             final int N = admins.size();
   3697             for (int i = 0; i < N; i++) {
   3698                 ActiveAdmin admin = admins.get(i);
   3699                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
   3700                     continue;
   3701                 }
   3702                 if (length < admin.minimumPasswordNonLetter) {
   3703                     length = admin.minimumPasswordNonLetter;
   3704                 }
   3705             }
   3706             return length;
   3707         }
   3708     }
   3709 
   3710     @Override
   3711     public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
   3712         if (!mHasFeature) {
   3713             return true;
   3714         }
   3715         enforceFullCrossUsersPermission(userHandle);
   3716 
   3717         synchronized (this) {
   3718             // This API can only be called by an active device admin,
   3719             // so try to retrieve it to check that the caller is one.
   3720             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
   3721             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
   3722             return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
   3723         }
   3724     }
   3725 
   3726     @Override
   3727     public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
   3728         if (!mHasFeature) {
   3729             return true;
   3730         }
   3731         enforceFullCrossUsersPermission(userHandle);
   3732         enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
   3733 
   3734         synchronized (this) {
   3735             int targetUser = getProfileParentId(userHandle);
   3736             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
   3737             return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
   3738         }
   3739     }
   3740 
   3741     private boolean isActivePasswordSufficientForUserLocked(
   3742             DevicePolicyData policy, int userHandle, boolean parent) {
   3743         final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
   3744         if (policy.mActivePasswordQuality < requiredPasswordQuality) {
   3745             return false;
   3746         }
   3747         if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
   3748                 && policy.mActivePasswordLength < getPasswordMinimumLength(
   3749                         null, userHandle, parent)) {
   3750             return false;
   3751         }
   3752         if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
   3753             return true;
   3754         }
   3755         return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
   3756                     null, userHandle, parent)
   3757                 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
   3758                         null, userHandle, parent)
   3759                 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
   3760                         null, userHandle, parent)
   3761                 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
   3762                         null, userHandle, parent)
   3763                 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
   3764                         null, userHandle, parent)
   3765                 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
   3766                         null, userHandle, parent);
   3767     }
   3768 
   3769     @Override
   3770     public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
   3771         enforceFullCrossUsersPermission(userHandle);
   3772         synchronized (this) {
   3773             if (!isCallerWithSystemUid()) {
   3774                 // This API can only be called by an active device admin,
   3775                 // so try to retrieve it to check that the caller is one.
   3776                 getActiveAdminForCallerLocked(
   3777                         null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
   3778             }
   3779 
   3780             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
   3781 
   3782             return policy.mFailedPasswordAttempts;
   3783         }
   3784     }
   3785 
   3786     @Override
   3787     public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
   3788         if (!mHasFeature) {
   3789             return;
   3790         }
   3791         Preconditions.checkNotNull(who, "ComponentName is null");
   3792         synchronized (this) {
   3793             // This API can only be called by an active device admin,
   3794             // so try to retrieve it to check that the caller is one.
   3795             getActiveAdminForCallerLocked(
   3796                     who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
   3797             ActiveAdmin ap = getActiveAdminForCallerLocked(
   3798                     who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
   3799             if (ap.maximumFailedPasswordsForWipe != num) {
   3800                 ap.maximumFailedPasswordsForWipe = num;
   3801                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   3802             }
   3803         }
   3804     }
   3805 
   3806     @Override
   3807     public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
   3808         if (!mHasFeature) {
   3809             return 0;
   3810         }
   3811         enforceFullCrossUsersPermission(userHandle);
   3812         synchronized (this) {
   3813             ActiveAdmin admin = (who != null)
   3814                     ? getActiveAdminUncheckedLocked(who, userHandle, parent)
   3815                     : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
   3816             return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
   3817         }
   3818     }
   3819 
   3820     @Override
   3821     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
   3822         if (!mHasFeature) {
   3823             return UserHandle.USER_NULL;
   3824         }
   3825         enforceFullCrossUsersPermission(userHandle);
   3826         synchronized (this) {
   3827             ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
   3828                     userHandle, parent);
   3829             return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
   3830         }
   3831     }
   3832 
   3833     /**
   3834      * Returns the admin with the strictest policy on maximum failed passwords for:
   3835      * <ul>
   3836      *   <li>this user if it has a separate profile challenge, or
   3837      *   <li>this user and all profiles that don't have their own challenge otherwise.
   3838      * </ul>
   3839      * <p>If the policy for the primary and any other profile are equal, it returns the admin for
   3840      * the primary profile.
   3841      * Returns {@code null} if no participating admin has that policy set.
   3842      */
   3843     private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
   3844             int userHandle, boolean parent) {
   3845         int count = 0;
   3846         ActiveAdmin strictestAdmin = null;
   3847 
   3848         // Return the strictest policy across all participating admins.
   3849         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   3850         final int N = admins.size();
   3851         for (int i = 0; i < N; i++) {
   3852             ActiveAdmin admin = admins.get(i);
   3853             if (admin.maximumFailedPasswordsForWipe ==
   3854                     ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
   3855                 continue;  // No max number of failed passwords policy set for this profile.
   3856             }
   3857 
   3858             // We always favor the primary profile if several profiles have the same value set.
   3859             int userId = admin.getUserHandle().getIdentifier();
   3860             if (count == 0 ||
   3861                     count > admin.maximumFailedPasswordsForWipe ||
   3862                     (count == admin.maximumFailedPasswordsForWipe &&
   3863                             getUserInfo(userId).isPrimary())) {
   3864                 count = admin.maximumFailedPasswordsForWipe;
   3865                 strictestAdmin = admin;
   3866             }
   3867         }
   3868         return strictestAdmin;
   3869     }
   3870 
   3871     private UserInfo getUserInfo(@UserIdInt int userId) {
   3872         final long token = mInjector.binderClearCallingIdentity();
   3873         try {
   3874             return mUserManager.getUserInfo(userId);
   3875         } finally {
   3876             mInjector.binderRestoreCallingIdentity(token);
   3877         }
   3878     }
   3879 
   3880     @Override
   3881     public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
   3882         if (!mHasFeature) {
   3883             return false;
   3884         }
   3885         final int callingUid = mInjector.binderGetCallingUid();
   3886         final int userHandle = mInjector.userHandleGetCallingUserId();
   3887 
   3888         String password = passwordOrNull != null ? passwordOrNull : "";
   3889 
   3890         // Password resetting to empty/null is not allowed for managed profiles.
   3891         if (TextUtils.isEmpty(password)) {
   3892             enforceNotManagedProfile(userHandle, "clear the active password");
   3893         }
   3894 
   3895         int quality;
   3896         synchronized (this) {
   3897             // If caller has PO (or DO) it can change the password, so see if that's the case first.
   3898             ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
   3899                     null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
   3900             final boolean preN;
   3901             if (admin != null) {
   3902                 preN = getTargetSdk(admin.info.getPackageName(),
   3903                         userHandle) <= android.os.Build.VERSION_CODES.M;
   3904             } else {
   3905                 // Otherwise, make sure the caller has any active admin with the right policy.
   3906                 admin = getActiveAdminForCallerLocked(null,
   3907                         DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
   3908                 preN = getTargetSdk(admin.info.getPackageName(),
   3909                         userHandle) <= android.os.Build.VERSION_CODES.M;
   3910 
   3911                 // As of N, password resetting to empty/null is not allowed anymore.
   3912                 // TODO Should we allow DO/PO to set an empty password?
   3913                 if (TextUtils.isEmpty(password)) {
   3914                     if (!preN) {
   3915                         throw new SecurityException("Cannot call with null password");
   3916                     } else {
   3917                         Slog.e(LOG_TAG, "Cannot call with null password");
   3918                         return false;
   3919                     }
   3920                 }
   3921                 // As of N, password cannot be changed by the admin if it is already set.
   3922                 if (isLockScreenSecureUnchecked(userHandle)) {
   3923                     if (!preN) {
   3924                         throw new SecurityException("Admin cannot change current password");
   3925                     } else {
   3926                         Slog.e(LOG_TAG, "Admin cannot change current password");
   3927                         return false;
   3928                     }
   3929                 }
   3930             }
   3931             // Do not allow to reset password when current user has a managed profile
   3932             if (!isManagedProfile(userHandle)) {
   3933                 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
   3934                     if (userInfo.isManagedProfile()) {
   3935                         if (!preN) {
   3936                             throw new IllegalStateException(
   3937                                     "Cannot reset password on user has managed profile");
   3938                         } else {
   3939                             Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
   3940                             return false;
   3941                         }
   3942                     }
   3943                 }
   3944             }
   3945             // Do not allow to reset password when user is locked
   3946             if (!mUserManager.isUserUnlocked(userHandle)) {
   3947                 if (!preN) {
   3948                     throw new IllegalStateException("Cannot reset password when user is locked");
   3949                 } else {
   3950                     Slog.e(LOG_TAG, "Cannot reset password when user is locked");
   3951                     return false;
   3952                 }
   3953             }
   3954 
   3955             quality = getPasswordQuality(null, userHandle, /* parent */ false);
   3956             if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
   3957                 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
   3958             }
   3959             if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
   3960                 int realQuality = LockPatternUtils.computePasswordQuality(password);
   3961                 if (realQuality < quality
   3962                         && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
   3963                     Slog.w(LOG_TAG, "resetPassword: password quality 0x"
   3964                             + Integer.toHexString(realQuality)
   3965                             + " does not meet required quality 0x"
   3966                             + Integer.toHexString(quality));
   3967                     return false;
   3968                 }
   3969                 quality = Math.max(realQuality, quality);
   3970             }
   3971             int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
   3972             if (password.length() < length) {
   3973                 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
   3974                         + " does not meet required length " + length);
   3975                 return false;
   3976             }
   3977             if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
   3978                 int letters = 0;
   3979                 int uppercase = 0;
   3980                 int lowercase = 0;
   3981                 int numbers = 0;
   3982                 int symbols = 0;
   3983                 int nonletter = 0;
   3984                 for (int i = 0; i < password.length(); i++) {
   3985                     char c = password.charAt(i);
   3986                     if (c >= 'A' && c <= 'Z') {
   3987                         letters++;
   3988                         uppercase++;
   3989                     } else if (c >= 'a' && c <= 'z') {
   3990                         letters++;
   3991                         lowercase++;
   3992                     } else if (c >= '0' && c <= '9') {
   3993                         numbers++;
   3994                         nonletter++;
   3995                     } else {
   3996                         symbols++;
   3997                         nonletter++;
   3998                     }
   3999                 }
   4000                 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
   4001                 if(letters < neededLetters) {
   4002                     Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
   4003                             + " does not meet required number of letters " + neededLetters);
   4004                     return false;
   4005                 }
   4006                 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
   4007                 if (numbers < neededNumbers) {
   4008                     Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
   4009                             + " does not meet required number of numerical digits "
   4010                             + neededNumbers);
   4011                     return false;
   4012                 }
   4013                 int neededLowerCase = getPasswordMinimumLowerCase(
   4014                         null, userHandle, /* parent */ false);
   4015                 if (lowercase < neededLowerCase) {
   4016                     Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
   4017                             + " does not meet required number of lowercase letters "
   4018                             + neededLowerCase);
   4019                     return false;
   4020                 }
   4021                 int neededUpperCase = getPasswordMinimumUpperCase(
   4022                         null, userHandle, /* parent */ false);
   4023                 if (uppercase < neededUpperCase) {
   4024                     Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
   4025                             + " does not meet required number of uppercase letters "
   4026                             + neededUpperCase);
   4027                     return false;
   4028                 }
   4029                 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
   4030                 if (symbols < neededSymbols) {
   4031                     Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
   4032                             + " does not meet required number of special symbols " + neededSymbols);
   4033                     return false;
   4034                 }
   4035                 int neededNonLetter = getPasswordMinimumNonLetter(
   4036                         null, userHandle, /* parent */ false);
   4037                 if (nonletter < neededNonLetter) {
   4038                     Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
   4039                             + " does not meet required number of non-letter characters "
   4040                             + neededNonLetter);
   4041                     return false;
   4042                 }
   4043             }
   4044         }
   4045 
   4046         DevicePolicyData policy = getUserData(userHandle);
   4047         if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
   4048             Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
   4049             return false;
   4050         }
   4051 
   4052         boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
   4053         boolean doNotAskCredentialsOnBoot =
   4054                 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
   4055         if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
   4056             setDoNotAskCredentialsOnBoot();
   4057         }
   4058 
   4059         // Don't do this with the lock held, because it is going to call
   4060         // back in to the service.
   4061         final long ident = mInjector.binderClearCallingIdentity();
   4062         try {
   4063             if (!TextUtils.isEmpty(password)) {
   4064                 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
   4065             } else {
   4066                 mLockPatternUtils.clearLock(userHandle);
   4067             }
   4068             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
   4069             if (requireEntry) {
   4070                 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
   4071                         UserHandle.USER_ALL);
   4072             }
   4073             synchronized (this) {
   4074                 int newOwner = requireEntry ? callingUid : -1;
   4075                 if (policy.mPasswordOwner != newOwner) {
   4076                     policy.mPasswordOwner = newOwner;
   4077                     saveSettingsLocked(userHandle);
   4078                 }
   4079             }
   4080         } finally {
   4081             mInjector.binderRestoreCallingIdentity(ident);
   4082         }
   4083 
   4084         return true;
   4085     }
   4086 
   4087     private boolean isLockScreenSecureUnchecked(int userId) {
   4088         long ident = mInjector.binderClearCallingIdentity();
   4089         try {
   4090             return mLockPatternUtils.isSecure(userId);
   4091         } finally {
   4092             mInjector.binderRestoreCallingIdentity(ident);
   4093         }
   4094     }
   4095 
   4096     private void setDoNotAskCredentialsOnBoot() {
   4097         synchronized (this) {
   4098             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
   4099             if (!policyData.doNotAskCredentialsOnBoot) {
   4100                 policyData.doNotAskCredentialsOnBoot = true;
   4101                 saveSettingsLocked(UserHandle.USER_SYSTEM);
   4102             }
   4103         }
   4104     }
   4105 
   4106     @Override
   4107     public boolean getDoNotAskCredentialsOnBoot() {
   4108         mContext.enforceCallingOrSelfPermission(
   4109                 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
   4110         synchronized (this) {
   4111             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
   4112             return policyData.doNotAskCredentialsOnBoot;
   4113         }
   4114     }
   4115 
   4116     @Override
   4117     public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
   4118         if (!mHasFeature) {
   4119             return;
   4120         }
   4121         Preconditions.checkNotNull(who, "ComponentName is null");
   4122         final int userHandle = mInjector.userHandleGetCallingUserId();
   4123         synchronized (this) {
   4124             ActiveAdmin ap = getActiveAdminForCallerLocked(
   4125                     who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
   4126             if (ap.maximumTimeToUnlock != timeMs) {
   4127                 ap.maximumTimeToUnlock = timeMs;
   4128                 saveSettingsLocked(userHandle);
   4129                 updateMaximumTimeToLockLocked(userHandle);
   4130             }
   4131         }
   4132     }
   4133 
   4134     void updateMaximumTimeToLockLocked(int userHandle) {
   4135         // Calculate the min timeout for all profiles - including the ones with a separate
   4136         // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
   4137         // challenge only and keep the screen on. However there is no easy way of doing that at the
   4138         // moment so we set the screen off timeout regardless of whether it affects the parent user
   4139         // or the profile challenge only.
   4140         long timeMs = Long.MAX_VALUE;
   4141         int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
   4142         for (int profileId : profileIds) {
   4143             DevicePolicyData policy = getUserDataUnchecked(profileId);
   4144             final int N = policy.mAdminList.size();
   4145             for (int i = 0; i < N; i++) {
   4146                 ActiveAdmin admin = policy.mAdminList.get(i);
   4147                 if (admin.maximumTimeToUnlock > 0
   4148                         && timeMs > admin.maximumTimeToUnlock) {
   4149                     timeMs = admin.maximumTimeToUnlock;
   4150                 }
   4151                 // If userInfo.id is a managed profile, we also need to look at
   4152                 // the policies set on the parent.
   4153                 if (admin.hasParentActiveAdmin()) {
   4154                     final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
   4155                     if (parentAdmin.maximumTimeToUnlock > 0
   4156                             && timeMs > parentAdmin.maximumTimeToUnlock) {
   4157                         timeMs = parentAdmin.maximumTimeToUnlock;
   4158                     }
   4159                 }
   4160             }
   4161         }
   4162 
   4163         // We only store the last maximum time to lock on the parent profile. So if calling from a
   4164         // managed profile, retrieve the policy for the parent.
   4165         DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
   4166         if (policy.mLastMaximumTimeToLock == timeMs) {
   4167             return;
   4168         }
   4169         policy.mLastMaximumTimeToLock = timeMs;
   4170 
   4171         final long ident = mInjector.binderClearCallingIdentity();
   4172         try {
   4173             if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
   4174                 // Make sure KEEP_SCREEN_ON is disabled, since that
   4175                 // would allow bypassing of the maximum time to lock.
   4176                 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
   4177             }
   4178 
   4179             mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
   4180                     (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
   4181         } finally {
   4182             mInjector.binderRestoreCallingIdentity(ident);
   4183         }
   4184     }
   4185 
   4186     @Override
   4187     public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
   4188         if (!mHasFeature) {
   4189             return 0;
   4190         }
   4191         enforceFullCrossUsersPermission(userHandle);
   4192         synchronized (this) {
   4193             if (who != null) {
   4194                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   4195                 return admin != null ? admin.maximumTimeToUnlock : 0;
   4196             }
   4197             // Return the strictest policy across all participating admins.
   4198             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
   4199                     userHandle, parent);
   4200             return getMaximumTimeToLockPolicyFromAdmins(admins);
   4201         }
   4202     }
   4203 
   4204     @Override
   4205     public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
   4206         if (!mHasFeature) {
   4207             return 0;
   4208         }
   4209         enforceFullCrossUsersPermission(userHandle);
   4210         synchronized (this) {
   4211             // All admins for this user.
   4212             ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
   4213             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
   4214                 DevicePolicyData policy = getUserData(userInfo.id);
   4215                 admins.addAll(policy.mAdminList);
   4216                 // If it is a managed profile, it may have parent active admins
   4217                 if (userInfo.isManagedProfile()) {
   4218                     for (ActiveAdmin admin : policy.mAdminList) {
   4219                         if (admin.hasParentActiveAdmin()) {
   4220                             admins.add(admin.getParentActiveAdmin());
   4221                         }
   4222                     }
   4223                 }
   4224             }
   4225             return getMaximumTimeToLockPolicyFromAdmins(admins);
   4226         }
   4227     }
   4228 
   4229     private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
   4230         long time = 0;
   4231         final int N = admins.size();
   4232         for (int i = 0; i < N; i++) {
   4233             ActiveAdmin admin = admins.get(i);
   4234             if (time == 0) {
   4235                 time = admin.maximumTimeToUnlock;
   4236             } else if (admin.maximumTimeToUnlock != 0
   4237                     && time > admin.maximumTimeToUnlock) {
   4238                 time = admin.maximumTimeToUnlock;
   4239             }
   4240         }
   4241         return time;
   4242     }
   4243 
   4244     @Override
   4245     public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
   4246             boolean parent) {
   4247         if (!mHasFeature) {
   4248             return;
   4249         }
   4250         Preconditions.checkNotNull(who, "ComponentName is null");
   4251         Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
   4252         // timeoutMs with value 0 means that the admin doesn't participate
   4253         // timeoutMs is clamped to the interval in case the internal constants change in the future
   4254         if (timeoutMs != 0 && timeoutMs < MINIMUM_STRONG_AUTH_TIMEOUT_MS) {
   4255             timeoutMs = MINIMUM_STRONG_AUTH_TIMEOUT_MS;
   4256         }
   4257         if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
   4258             timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
   4259         }
   4260 
   4261         final int userHandle = mInjector.userHandleGetCallingUserId();
   4262         synchronized (this) {
   4263             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   4264                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
   4265             if (ap.strongAuthUnlockTimeout != timeoutMs) {
   4266                 ap.strongAuthUnlockTimeout = timeoutMs;
   4267                 saveSettingsLocked(userHandle);
   4268             }
   4269         }
   4270     }
   4271 
   4272     /**
   4273      * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
   4274      * admins if who is null.
   4275      * Returns 0 if not configured for the provided admin.
   4276      */
   4277     @Override
   4278     public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
   4279         if (!mHasFeature) {
   4280             return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
   4281         }
   4282         enforceFullCrossUsersPermission(userId);
   4283         synchronized (this) {
   4284             if (who != null) {
   4285                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
   4286                 return admin != null ? admin.strongAuthUnlockTimeout : 0;
   4287             }
   4288 
   4289             // Return the strictest policy across all participating admins.
   4290             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
   4291 
   4292             long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
   4293             for (int i = 0; i < admins.size(); i++) {
   4294                 final long timeout = admins.get(i).strongAuthUnlockTimeout;
   4295                 if (timeout != 0) { // take only participating admins into account
   4296                     strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
   4297                 }
   4298             }
   4299             return Math.max(strongAuthUnlockTimeout, MINIMUM_STRONG_AUTH_TIMEOUT_MS);
   4300         }
   4301     }
   4302 
   4303     @Override
   4304     public void lockNow(boolean parent) {
   4305         if (!mHasFeature) {
   4306             return;
   4307         }
   4308         synchronized (this) {
   4309             // This API can only be called by an active device admin,
   4310             // so try to retrieve it to check that the caller is one.
   4311             getActiveAdminForCallerLocked(
   4312                     null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
   4313 
   4314             int userToLock = mInjector.userHandleGetCallingUserId();
   4315 
   4316             // Unless this is a managed profile with work challenge enabled, lock all users.
   4317             if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
   4318                 userToLock = UserHandle.USER_ALL;
   4319             }
   4320             final long ident = mInjector.binderClearCallingIdentity();
   4321             try {
   4322                 mLockPatternUtils.requireStrongAuth(
   4323                         STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
   4324                 if (userToLock == UserHandle.USER_ALL) {
   4325                     // Power off the display
   4326                     mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
   4327                             PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
   4328                     mInjector.getIWindowManager().lockNow(null);
   4329                 } else {
   4330                     mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
   4331                 }
   4332             } catch (RemoteException e) {
   4333             } finally {
   4334                 mInjector.binderRestoreCallingIdentity(ident);
   4335             }
   4336         }
   4337     }
   4338 
   4339     @Override
   4340     public void enforceCanManageCaCerts(ComponentName who) {
   4341         if (who == null) {
   4342             if (!isCallerDelegatedCertInstaller()) {
   4343                 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
   4344             }
   4345         } else {
   4346             synchronized (this) {
   4347                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4348             }
   4349         }
   4350     }
   4351 
   4352     private void enforceCanManageInstalledKeys(ComponentName who) {
   4353         if (who == null) {
   4354             if (!isCallerDelegatedCertInstaller()) {
   4355                 throw new SecurityException("who == null, but caller is not cert installer");
   4356             }
   4357         } else {
   4358             synchronized (this) {
   4359                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4360             }
   4361         }
   4362     }
   4363 
   4364     private boolean isCallerDelegatedCertInstaller() {
   4365         final int callingUid = mInjector.binderGetCallingUid();
   4366         final int userHandle = UserHandle.getUserId(callingUid);
   4367         synchronized (this) {
   4368             final DevicePolicyData policy = getUserData(userHandle);
   4369             if (policy.mDelegatedCertInstallerPackage == null) {
   4370                 return false;
   4371             }
   4372 
   4373             try {
   4374                 int uid = mContext.getPackageManager().getPackageUidAsUser(
   4375                         policy.mDelegatedCertInstallerPackage, userHandle);
   4376                 return uid == callingUid;
   4377             } catch (NameNotFoundException e) {
   4378                 return false;
   4379             }
   4380         }
   4381     }
   4382 
   4383     @Override
   4384     public boolean approveCaCert(String alias, int userId, boolean approval) {
   4385         enforceManageUsers();
   4386         synchronized (this) {
   4387             Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
   4388             boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
   4389             if (!changed) {
   4390                 return false;
   4391             }
   4392             saveSettingsLocked(userId);
   4393         }
   4394         new MonitoringCertNotificationTask().execute(userId);
   4395         return true;
   4396     }
   4397 
   4398     @Override
   4399     public boolean isCaCertApproved(String alias, int userId) {
   4400         enforceManageUsers();
   4401         synchronized (this) {
   4402             return getUserData(userId).mAcceptedCaCertificates.contains(alias);
   4403         }
   4404     }
   4405 
   4406     private void removeCaApprovalsIfNeeded(int userId) {
   4407         for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
   4408             boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
   4409             if (userInfo.isManagedProfile()){
   4410                 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
   4411             }
   4412             if (!isSecure) {
   4413                 synchronized (this) {
   4414                     getUserData(userInfo.id).mAcceptedCaCertificates.clear();
   4415                     saveSettingsLocked(userInfo.id);
   4416                 }
   4417 
   4418                 new MonitoringCertNotificationTask().execute(userInfo.id);
   4419             }
   4420         }
   4421     }
   4422 
   4423     @Override
   4424     public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
   4425         enforceCanManageCaCerts(admin);
   4426 
   4427         byte[] pemCert;
   4428         try {
   4429             X509Certificate cert = parseCert(certBuffer);
   4430             pemCert = Credentials.convertToPem(cert);
   4431         } catch (CertificateException ce) {
   4432             Log.e(LOG_TAG, "Problem converting cert", ce);
   4433             return false;
   4434         } catch (IOException ioe) {
   4435             Log.e(LOG_TAG, "Problem reading cert", ioe);
   4436             return false;
   4437         }
   4438 
   4439         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
   4440         final long id = mInjector.binderClearCallingIdentity();
   4441         try {
   4442             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
   4443             try {
   4444                 keyChainConnection.getService().installCaCertificate(pemCert);
   4445                 return true;
   4446             } catch (RemoteException e) {
   4447                 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
   4448             } finally {
   4449                 keyChainConnection.close();
   4450             }
   4451         } catch (InterruptedException e1) {
   4452             Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
   4453             Thread.currentThread().interrupt();
   4454         } finally {
   4455             mInjector.binderRestoreCallingIdentity(id);
   4456         }
   4457         return false;
   4458     }
   4459 
   4460     private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
   4461         CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
   4462         return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
   4463                 certBuffer));
   4464     }
   4465 
   4466     @Override
   4467     public void uninstallCaCerts(ComponentName admin, String[] aliases) {
   4468         enforceCanManageCaCerts(admin);
   4469 
   4470         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
   4471         final long id = mInjector.binderClearCallingIdentity();
   4472         try {
   4473             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
   4474             try {
   4475                 for (int i = 0 ; i < aliases.length; i++) {
   4476                     keyChainConnection.getService().deleteCaCertificate(aliases[i]);
   4477                 }
   4478             } catch (RemoteException e) {
   4479                 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
   4480             } finally {
   4481                 keyChainConnection.close();
   4482             }
   4483         } catch (InterruptedException ie) {
   4484             Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
   4485             Thread.currentThread().interrupt();
   4486         } finally {
   4487             mInjector.binderRestoreCallingIdentity(id);
   4488         }
   4489     }
   4490 
   4491     @Override
   4492     public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
   4493             String alias, boolean requestAccess) {
   4494         enforceCanManageInstalledKeys(who);
   4495 
   4496         final int callingUid = mInjector.binderGetCallingUid();
   4497         final long id = mInjector.binderClearCallingIdentity();
   4498         try {
   4499             final KeyChainConnection keyChainConnection =
   4500                     KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
   4501             try {
   4502                 IKeyChainService keyChain = keyChainConnection.getService();
   4503                 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
   4504                     return false;
   4505                 }
   4506                 if (requestAccess) {
   4507                     keyChain.setGrant(callingUid, alias, true);
   4508                 }
   4509                 return true;
   4510             } catch (RemoteException e) {
   4511                 Log.e(LOG_TAG, "Installing certificate", e);
   4512             } finally {
   4513                 keyChainConnection.close();
   4514             }
   4515         } catch (InterruptedException e) {
   4516             Log.w(LOG_TAG, "Interrupted while installing certificate", e);
   4517             Thread.currentThread().interrupt();
   4518         } finally {
   4519             mInjector.binderRestoreCallingIdentity(id);
   4520         }
   4521         return false;
   4522     }
   4523 
   4524     @Override
   4525     public boolean removeKeyPair(ComponentName who, String alias) {
   4526         enforceCanManageInstalledKeys(who);
   4527 
   4528         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
   4529         final long id = Binder.clearCallingIdentity();
   4530         try {
   4531             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
   4532             try {
   4533                 IKeyChainService keyChain = keyChainConnection.getService();
   4534                 return keyChain.removeKeyPair(alias);
   4535             } catch (RemoteException e) {
   4536                 Log.e(LOG_TAG, "Removing keypair", e);
   4537             } finally {
   4538                 keyChainConnection.close();
   4539             }
   4540         } catch (InterruptedException e) {
   4541             Log.w(LOG_TAG, "Interrupted while removing keypair", e);
   4542             Thread.currentThread().interrupt();
   4543         } finally {
   4544             Binder.restoreCallingIdentity(id);
   4545         }
   4546         return false;
   4547     }
   4548 
   4549     @Override
   4550     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
   4551             final IBinder response) {
   4552         // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
   4553         if (!isCallerWithSystemUid()) {
   4554             return;
   4555         }
   4556 
   4557         final UserHandle caller = mInjector.binderGetCallingUserHandle();
   4558         // If there is a profile owner, redirect to that; otherwise query the device owner.
   4559         ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
   4560         if (aliasChooser == null && caller.isSystem()) {
   4561             ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
   4562             if (deviceOwnerAdmin != null) {
   4563                 aliasChooser = deviceOwnerAdmin.info.getComponent();
   4564             }
   4565         }
   4566         if (aliasChooser == null) {
   4567             sendPrivateKeyAliasResponse(null, response);
   4568             return;
   4569         }
   4570 
   4571         Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
   4572         intent.setComponent(aliasChooser);
   4573         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
   4574         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
   4575         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
   4576         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
   4577         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
   4578 
   4579         final long id = mInjector.binderClearCallingIdentity();
   4580         try {
   4581             mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
   4582                 @Override
   4583                 public void onReceive(Context context, Intent intent) {
   4584                     final String chosenAlias = getResultData();
   4585                     sendPrivateKeyAliasResponse(chosenAlias, response);
   4586                 }
   4587             }, null, Activity.RESULT_OK, null, null);
   4588         } finally {
   4589             mInjector.binderRestoreCallingIdentity(id);
   4590         }
   4591     }
   4592 
   4593     private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
   4594         final IKeyChainAliasCallback keyChainAliasResponse =
   4595                 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
   4596         new AsyncTask<Void, Void, Void>() {
   4597             @Override
   4598             protected Void doInBackground(Void... unused) {
   4599                 try {
   4600                     keyChainAliasResponse.alias(alias);
   4601                 } catch (Exception e) {
   4602                     // Catch everything (not just RemoteException): caller could throw a
   4603                     // RuntimeException back across processes.
   4604                     Log.e(LOG_TAG, "error while responding to callback", e);
   4605                 }
   4606                 return null;
   4607             }
   4608         }.execute();
   4609     }
   4610 
   4611     @Override
   4612     public void setCertInstallerPackage(ComponentName who, String installerPackage)
   4613             throws SecurityException {
   4614         int userHandle = UserHandle.getCallingUserId();
   4615         synchronized (this) {
   4616             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4617             if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
   4618                 if (installerPackage != null &&
   4619                         !isPackageInstalledForUser(installerPackage, userHandle)) {
   4620                     throw new IllegalArgumentException("Package " + installerPackage
   4621                             + " is not installed on the current user");
   4622                 }
   4623             }
   4624             DevicePolicyData policy = getUserData(userHandle);
   4625             policy.mDelegatedCertInstallerPackage = installerPackage;
   4626             saveSettingsLocked(userHandle);
   4627         }
   4628     }
   4629 
   4630     @Override
   4631     public String getCertInstallerPackage(ComponentName who) throws SecurityException {
   4632         int userHandle = UserHandle.getCallingUserId();
   4633         synchronized (this) {
   4634             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4635             DevicePolicyData policy = getUserData(userHandle);
   4636             return policy.mDelegatedCertInstallerPackage;
   4637         }
   4638     }
   4639 
   4640     /**
   4641      * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
   4642      * not installed and therefore not available.
   4643      *
   4644      * @throws SecurityException if the caller is not a profile or device owner.
   4645      * @throws UnsupportedOperationException if the package does not support being set as always-on.
   4646      */
   4647     @Override
   4648     public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
   4649             throws SecurityException {
   4650         synchronized (this) {
   4651             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4652         }
   4653 
   4654         final int userId = mInjector.userHandleGetCallingUserId();
   4655         final long token = mInjector.binderClearCallingIdentity();
   4656         try {
   4657             if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
   4658                 return false;
   4659             }
   4660             ConnectivityManager connectivityManager = (ConnectivityManager)
   4661                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
   4662             if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
   4663                 throw new UnsupportedOperationException();
   4664             }
   4665         } finally {
   4666             mInjector.binderRestoreCallingIdentity(token);
   4667         }
   4668         return true;
   4669     }
   4670 
   4671     @Override
   4672     public String getAlwaysOnVpnPackage(ComponentName admin)
   4673             throws SecurityException {
   4674         synchronized (this) {
   4675             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4676         }
   4677 
   4678         final int userId = mInjector.userHandleGetCallingUserId();
   4679         final long token = mInjector.binderClearCallingIdentity();
   4680         try{
   4681             ConnectivityManager connectivityManager = (ConnectivityManager)
   4682                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
   4683             return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
   4684         } finally {
   4685             mInjector.binderRestoreCallingIdentity(token);
   4686         }
   4687     }
   4688 
   4689     private void wipeDataLocked(boolean wipeExtRequested, String reason) {
   4690         if (wipeExtRequested) {
   4691             StorageManager sm = (StorageManager) mContext.getSystemService(
   4692                     Context.STORAGE_SERVICE);
   4693             sm.wipeAdoptableDisks();
   4694         }
   4695         try {
   4696             RecoverySystem.rebootWipeUserData(mContext, reason);
   4697         } catch (IOException | SecurityException e) {
   4698             Slog.w(LOG_TAG, "Failed requesting data wipe", e);
   4699         }
   4700     }
   4701 
   4702     @Override
   4703     public void wipeData(int flags) {
   4704         if (!mHasFeature) {
   4705             return;
   4706         }
   4707         final int userHandle = mInjector.userHandleGetCallingUserId();
   4708         enforceFullCrossUsersPermission(userHandle);
   4709         synchronized (this) {
   4710             // This API can only be called by an active device admin,
   4711             // so try to retrieve it to check that the caller is one.
   4712             final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
   4713                     DeviceAdminInfo.USES_POLICY_WIPE_DATA);
   4714 
   4715             final String source = admin.info.getComponent().flattenToShortString();
   4716 
   4717             long ident = mInjector.binderClearCallingIdentity();
   4718             try {
   4719                 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
   4720                     if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
   4721                         throw new SecurityException(
   4722                                "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
   4723                     }
   4724                     PersistentDataBlockManager manager = (PersistentDataBlockManager)
   4725                             mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
   4726                     if (manager != null) {
   4727                         manager.wipe();
   4728                     }
   4729                 }
   4730                 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
   4731                 wipeDeviceOrUserLocked(wipeExtRequested, userHandle,
   4732                         "DevicePolicyManager.wipeData() from " + source);
   4733             } finally {
   4734                 mInjector.binderRestoreCallingIdentity(ident);
   4735             }
   4736         }
   4737     }
   4738 
   4739     private void wipeDeviceOrUserLocked(boolean wipeExtRequested, final int userHandle, String reason) {
   4740         if (userHandle == UserHandle.USER_SYSTEM) {
   4741             wipeDataLocked(wipeExtRequested, reason);
   4742         } else {
   4743             mHandler.post(new Runnable() {
   4744                 @Override
   4745                 public void run() {
   4746                     try {
   4747                         IActivityManager am = mInjector.getIActivityManager();
   4748                         if (am.getCurrentUser().id == userHandle) {
   4749                             am.switchUser(UserHandle.USER_SYSTEM);
   4750                         }
   4751 
   4752                         boolean isManagedProfile = isManagedProfile(userHandle);
   4753                         if (!mUserManager.removeUser(userHandle)) {
   4754                             Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
   4755                         } else if (isManagedProfile) {
   4756                             sendWipeProfileNotification();
   4757                         }
   4758                     } catch (RemoteException re) {
   4759                         // Shouldn't happen
   4760                     }
   4761                 }
   4762             });
   4763         }
   4764     }
   4765 
   4766     private void sendWipeProfileNotification() {
   4767         String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
   4768         Notification notification = new Notification.Builder(mContext)
   4769                 .setSmallIcon(android.R.drawable.stat_sys_warning)
   4770                 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
   4771                 .setContentText(contentText)
   4772                 .setColor(mContext.getColor(R.color.system_notification_accent_color))
   4773                 .setStyle(new Notification.BigTextStyle().bigText(contentText))
   4774                 .build();
   4775         mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
   4776     }
   4777 
   4778     private void clearWipeProfileNotification() {
   4779         mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
   4780     }
   4781 
   4782     @Override
   4783     public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
   4784         if (!mHasFeature) {
   4785             return;
   4786         }
   4787         enforceFullCrossUsersPermission(userHandle);
   4788         mContext.enforceCallingOrSelfPermission(
   4789                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   4790 
   4791         synchronized (this) {
   4792             ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
   4793             if (admin == null) {
   4794                 result.sendResult(null);
   4795                 return;
   4796             }
   4797             Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
   4798             intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
   4799             intent.setComponent(admin.info.getComponent());
   4800             mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
   4801                     null, new BroadcastReceiver() {
   4802                 @Override
   4803                 public void onReceive(Context context, Intent intent) {
   4804                     result.sendResult(getResultExtras(false));
   4805                 }
   4806             }, null, Activity.RESULT_OK, null, null);
   4807         }
   4808     }
   4809 
   4810     @Override
   4811     public void setActivePasswordState(int quality, int length, int letters, int uppercase,
   4812             int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
   4813         if (!mHasFeature) {
   4814             return;
   4815         }
   4816         enforceFullCrossUsersPermission(userHandle);
   4817 
   4818         // Managed Profile password can only be changed when it has a separate challenge.
   4819         if (!isSeparateProfileChallengeEnabled(userHandle)) {
   4820             enforceNotManagedProfile(userHandle, "set the active password");
   4821         }
   4822 
   4823         mContext.enforceCallingOrSelfPermission(
   4824                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   4825         validateQualityConstant(quality);
   4826 
   4827         DevicePolicyData policy = getUserData(userHandle);
   4828 
   4829         long ident = mInjector.binderClearCallingIdentity();
   4830         try {
   4831             synchronized (this) {
   4832                 policy.mActivePasswordQuality = quality;
   4833                 policy.mActivePasswordLength = length;
   4834                 policy.mActivePasswordLetters = letters;
   4835                 policy.mActivePasswordLowerCase = lowercase;
   4836                 policy.mActivePasswordUpperCase = uppercase;
   4837                 policy.mActivePasswordNumeric = numbers;
   4838                 policy.mActivePasswordSymbols = symbols;
   4839                 policy.mActivePasswordNonLetter = nonletter;
   4840                 policy.mFailedPasswordAttempts = 0;
   4841                 saveSettingsLocked(userHandle);
   4842                 updatePasswordExpirationsLocked(userHandle);
   4843                 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
   4844 
   4845                 // Send a broadcast to each profile using this password as its primary unlock.
   4846                 sendAdminCommandForLockscreenPoliciesLocked(
   4847                         DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
   4848                         DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
   4849             }
   4850             removeCaApprovalsIfNeeded(userHandle);
   4851         } finally {
   4852             mInjector.binderRestoreCallingIdentity(ident);
   4853         }
   4854     }
   4855 
   4856     /**
   4857      * Called any time the device password is updated. Resets all password expiration clocks.
   4858      */
   4859     private void updatePasswordExpirationsLocked(int userHandle) {
   4860         ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
   4861         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
   4862                 userHandle, /* parent */ false);
   4863         final int N = admins.size();
   4864         for (int i = 0; i < N; i++) {
   4865             ActiveAdmin admin = admins.get(i);
   4866             if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
   4867                 affectedUserIds.add(admin.getUserHandle().getIdentifier());
   4868                 long timeout = admin.passwordExpirationTimeout;
   4869                 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
   4870                 admin.passwordExpirationDate = expiration;
   4871             }
   4872         }
   4873         for (int affectedUserId : affectedUserIds) {
   4874             saveSettingsLocked(affectedUserId);
   4875         }
   4876     }
   4877 
   4878     @Override
   4879     public void reportFailedPasswordAttempt(int userHandle) {
   4880         enforceFullCrossUsersPermission(userHandle);
   4881         if (!isSeparateProfileChallengeEnabled(userHandle)) {
   4882             enforceNotManagedProfile(userHandle,
   4883                     "report failed password attempt if separate profile challenge is not in place");
   4884         }
   4885         mContext.enforceCallingOrSelfPermission(
   4886                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   4887 
   4888         final long ident = mInjector.binderClearCallingIdentity();
   4889         try {
   4890             boolean wipeData = false;
   4891             int identifier = 0;
   4892             synchronized (this) {
   4893                 DevicePolicyData policy = getUserData(userHandle);
   4894                 policy.mFailedPasswordAttempts++;
   4895                 saveSettingsLocked(userHandle);
   4896                 if (mHasFeature) {
   4897                     ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
   4898                             userHandle, /* parent */ false);
   4899                     int max = strictestAdmin != null
   4900                             ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
   4901                     if (max > 0 && policy.mFailedPasswordAttempts >= max) {
   4902                         // Wipe the user/profile associated with the policy that was violated. This
   4903                         // is not necessarily calling user: if the policy that fired was from a
   4904                         // managed profile rather than the main user profile, we wipe former only.
   4905                         wipeData = true;
   4906                         identifier = strictestAdmin.getUserHandle().getIdentifier();
   4907                     }
   4908 
   4909                     sendAdminCommandForLockscreenPoliciesLocked(
   4910                             DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
   4911                             DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
   4912                 }
   4913             }
   4914             if (wipeData) {
   4915                 // Call without holding lock.
   4916                 wipeDeviceOrUserLocked(false, identifier,
   4917                         "reportFailedPasswordAttempt()");
   4918             }
   4919         } finally {
   4920             mInjector.binderRestoreCallingIdentity(ident);
   4921         }
   4922 
   4923         if (mInjector.securityLogIsLoggingEnabled()) {
   4924             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
   4925                     /*method strength*/ 1);
   4926         }
   4927     }
   4928 
   4929     @Override
   4930     public void reportSuccessfulPasswordAttempt(int userHandle) {
   4931         enforceFullCrossUsersPermission(userHandle);
   4932         mContext.enforceCallingOrSelfPermission(
   4933                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   4934 
   4935         synchronized (this) {
   4936             DevicePolicyData policy = getUserData(userHandle);
   4937             if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
   4938                 long ident = mInjector.binderClearCallingIdentity();
   4939                 try {
   4940                     policy.mFailedPasswordAttempts = 0;
   4941                     policy.mPasswordOwner = -1;
   4942                     saveSettingsLocked(userHandle);
   4943                     if (mHasFeature) {
   4944                         sendAdminCommandForLockscreenPoliciesLocked(
   4945                                 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
   4946                                 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
   4947                     }
   4948                 } finally {
   4949                     mInjector.binderRestoreCallingIdentity(ident);
   4950                 }
   4951             }
   4952         }
   4953 
   4954         if (mInjector.securityLogIsLoggingEnabled()) {
   4955             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
   4956                     /*method strength*/ 1);
   4957         }
   4958     }
   4959 
   4960     @Override
   4961     public void reportFailedFingerprintAttempt(int userHandle) {
   4962         enforceFullCrossUsersPermission(userHandle);
   4963         mContext.enforceCallingOrSelfPermission(
   4964                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   4965         if (mInjector.securityLogIsLoggingEnabled()) {
   4966             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
   4967                     /*method strength*/ 0);
   4968         }
   4969     }
   4970 
   4971     @Override
   4972     public void reportSuccessfulFingerprintAttempt(int userHandle) {
   4973         enforceFullCrossUsersPermission(userHandle);
   4974         mContext.enforceCallingOrSelfPermission(
   4975                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   4976         if (mInjector.securityLogIsLoggingEnabled()) {
   4977             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
   4978                     /*method strength*/ 0);
   4979         }
   4980     }
   4981 
   4982     @Override
   4983     public void reportKeyguardDismissed(int userHandle) {
   4984         enforceFullCrossUsersPermission(userHandle);
   4985         mContext.enforceCallingOrSelfPermission(
   4986                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   4987 
   4988         if (mInjector.securityLogIsLoggingEnabled()) {
   4989             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
   4990         }
   4991     }
   4992 
   4993     @Override
   4994     public void reportKeyguardSecured(int userHandle) {
   4995         enforceFullCrossUsersPermission(userHandle);
   4996         mContext.enforceCallingOrSelfPermission(
   4997                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   4998 
   4999         if (mInjector.securityLogIsLoggingEnabled()) {
   5000             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
   5001         }
   5002     }
   5003 
   5004     @Override
   5005     public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
   5006             String exclusionList) {
   5007         if (!mHasFeature) {
   5008             return null;
   5009         }
   5010         synchronized(this) {
   5011             Preconditions.checkNotNull(who, "ComponentName is null");
   5012 
   5013             // Only check if system user has set global proxy. We don't allow other users to set it.
   5014             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
   5015             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   5016                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
   5017 
   5018             // Scan through active admins and find if anyone has already
   5019             // set the global proxy.
   5020             Set<ComponentName> compSet = policy.mAdminMap.keySet();
   5021             for (ComponentName component : compSet) {
   5022                 ActiveAdmin ap = policy.mAdminMap.get(component);
   5023                 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
   5024                     // Another admin already sets the global proxy
   5025                     // Return it to the caller.
   5026                     return component;
   5027                 }
   5028             }
   5029 
   5030             // If the user is not system, don't set the global proxy. Fail silently.
   5031             if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
   5032                 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
   5033                         + UserHandle.getCallingUserId() + " is not permitted.");
   5034                 return null;
   5035             }
   5036             if (proxySpec == null) {
   5037                 admin.specifiesGlobalProxy = false;
   5038                 admin.globalProxySpec = null;
   5039                 admin.globalProxyExclusionList = null;
   5040             } else {
   5041 
   5042                 admin.specifiesGlobalProxy = true;
   5043                 admin.globalProxySpec = proxySpec;
   5044                 admin.globalProxyExclusionList = exclusionList;
   5045             }
   5046 
   5047             // Reset the global proxy accordingly
   5048             // Do this using system permissions, as apps cannot write to secure settings
   5049             long origId = mInjector.binderClearCallingIdentity();
   5050             try {
   5051                 resetGlobalProxyLocked(policy);
   5052             } finally {
   5053                 mInjector.binderRestoreCallingIdentity(origId);
   5054             }
   5055             return null;
   5056         }
   5057     }
   5058 
   5059     @Override
   5060     public ComponentName getGlobalProxyAdmin(int userHandle) {
   5061         if (!mHasFeature) {
   5062             return null;
   5063         }
   5064         enforceFullCrossUsersPermission(userHandle);
   5065         synchronized(this) {
   5066             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
   5067             // Scan through active admins and find if anyone has already
   5068             // set the global proxy.
   5069             final int N = policy.mAdminList.size();
   5070             for (int i = 0; i < N; i++) {
   5071                 ActiveAdmin ap = policy.mAdminList.get(i);
   5072                 if (ap.specifiesGlobalProxy) {
   5073                     // Device admin sets the global proxy
   5074                     // Return it to the caller.
   5075                     return ap.info.getComponent();
   5076                 }
   5077             }
   5078         }
   5079         // No device admin sets the global proxy.
   5080         return null;
   5081     }
   5082 
   5083     @Override
   5084     public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
   5085         synchronized (this) {
   5086             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5087         }
   5088         long token = mInjector.binderClearCallingIdentity();
   5089         try {
   5090             ConnectivityManager connectivityManager = (ConnectivityManager)
   5091                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
   5092             connectivityManager.setGlobalProxy(proxyInfo);
   5093         } finally {
   5094             mInjector.binderRestoreCallingIdentity(token);
   5095         }
   5096     }
   5097 
   5098     private void resetGlobalProxyLocked(DevicePolicyData policy) {
   5099         final int N = policy.mAdminList.size();
   5100         for (int i = 0; i < N; i++) {
   5101             ActiveAdmin ap = policy.mAdminList.get(i);
   5102             if (ap.specifiesGlobalProxy) {
   5103                 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
   5104                 return;
   5105             }
   5106         }
   5107         // No device admins defining global proxies - reset global proxy settings to none
   5108         saveGlobalProxyLocked(null, null);
   5109     }
   5110 
   5111     private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
   5112         if (exclusionList == null) {
   5113             exclusionList = "";
   5114         }
   5115         if (proxySpec == null) {
   5116             proxySpec = "";
   5117         }
   5118         // Remove white spaces
   5119         proxySpec = proxySpec.trim();
   5120         String data[] = proxySpec.split(":");
   5121         int proxyPort = 8080;
   5122         if (data.length > 1) {
   5123             try {
   5124                 proxyPort = Integer.parseInt(data[1]);
   5125             } catch (NumberFormatException e) {}
   5126         }
   5127         exclusionList = exclusionList.trim();
   5128 
   5129         ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
   5130         if (!proxyProperties.isValid()) {
   5131             Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
   5132             return;
   5133         }
   5134         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
   5135         mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
   5136         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
   5137                 exclusionList);
   5138     }
   5139 
   5140     /**
   5141      * Set the storage encryption request for a single admin.  Returns the new total request
   5142      * status (for all admins).
   5143      */
   5144     @Override
   5145     public int setStorageEncryption(ComponentName who, boolean encrypt) {
   5146         if (!mHasFeature) {
   5147             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
   5148         }
   5149         Preconditions.checkNotNull(who, "ComponentName is null");
   5150         final int userHandle = UserHandle.getCallingUserId();
   5151         synchronized (this) {
   5152             // Check for permissions
   5153             // Only system user can set storage encryption
   5154             if (userHandle != UserHandle.USER_SYSTEM) {
   5155                 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
   5156                         + UserHandle.getCallingUserId() + " is not permitted.");
   5157                 return 0;
   5158             }
   5159 
   5160             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   5161                     DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
   5162 
   5163             // Quick exit:  If the filesystem does not support encryption, we can exit early.
   5164             if (!isEncryptionSupported()) {
   5165                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
   5166             }
   5167 
   5168             // (1) Record the value for the admin so it's sticky
   5169             if (ap.encryptionRequested != encrypt) {
   5170                 ap.encryptionRequested = encrypt;
   5171                 saveSettingsLocked(userHandle);
   5172             }
   5173 
   5174             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
   5175             // (2) Compute "max" for all admins
   5176             boolean newRequested = false;
   5177             final int N = policy.mAdminList.size();
   5178             for (int i = 0; i < N; i++) {
   5179                 newRequested |= policy.mAdminList.get(i).encryptionRequested;
   5180             }
   5181 
   5182             // Notify OS of new request
   5183             setEncryptionRequested(newRequested);
   5184 
   5185             // Return the new global request status
   5186             return newRequested
   5187                     ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
   5188                     : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
   5189         }
   5190     }
   5191 
   5192     /**
   5193      * Get the current storage encryption request status for a given admin, or aggregate of all
   5194      * active admins.
   5195      */
   5196     @Override
   5197     public boolean getStorageEncryption(ComponentName who, int userHandle) {
   5198         if (!mHasFeature) {
   5199             return false;
   5200         }
   5201         enforceFullCrossUsersPermission(userHandle);
   5202         synchronized (this) {
   5203             // Check for permissions if a particular caller is specified
   5204             if (who != null) {
   5205                 // When checking for a single caller, status is based on caller's request
   5206                 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
   5207                 return ap != null ? ap.encryptionRequested : false;
   5208             }
   5209 
   5210             // If no particular caller is specified, return the aggregate set of requests.
   5211             // This is short circuited by returning true on the first hit.
   5212             DevicePolicyData policy = getUserData(userHandle);
   5213             final int N = policy.mAdminList.size();
   5214             for (int i = 0; i < N; i++) {
   5215                 if (policy.mAdminList.get(i).encryptionRequested) {
   5216                     return true;
   5217                 }
   5218             }
   5219             return false;
   5220         }
   5221     }
   5222 
   5223     /**
   5224      * Get the current encryption status of the device.
   5225      */
   5226     @Override
   5227     public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
   5228         if (!mHasFeature) {
   5229             // Ok to return current status.
   5230         }
   5231         enforceFullCrossUsersPermission(userHandle);
   5232 
   5233         // It's not critical here, but let's make sure the package name is correct, in case
   5234         // we start using it for different purposes.
   5235         ensureCallerPackage(callerPackage);
   5236 
   5237         final ApplicationInfo ai;
   5238         try {
   5239             ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
   5240         } catch (RemoteException e) {
   5241             throw new SecurityException(e);
   5242         }
   5243 
   5244         boolean legacyApp = false;
   5245         if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
   5246             legacyApp = true;
   5247         }
   5248 
   5249         final int rawStatus = getEncryptionStatus();
   5250         if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
   5251             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
   5252         }
   5253         return rawStatus;
   5254     }
   5255 
   5256     /**
   5257      * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
   5258      */
   5259     private boolean isEncryptionSupported() {
   5260         // Note, this can be implemented as
   5261         //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
   5262         // But is provided as a separate internal method if there's a faster way to do a
   5263         // simple check for supported-or-not.
   5264         return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
   5265     }
   5266 
   5267     /**
   5268      * Hook to low-levels:  Reporting the current status of encryption.
   5269      * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
   5270      * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
   5271      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
   5272      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
   5273      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
   5274      */
   5275     private int getEncryptionStatus() {
   5276         if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
   5277             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
   5278         } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
   5279             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
   5280         } else if (mInjector.storageManagerIsEncrypted()) {
   5281             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
   5282         } else if (mInjector.storageManagerIsEncryptable()) {
   5283             return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
   5284         } else {
   5285             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
   5286         }
   5287     }
   5288 
   5289     /**
   5290      * Hook to low-levels:  If needed, record the new admin setting for encryption.
   5291      */
   5292     private void setEncryptionRequested(boolean encrypt) {
   5293     }
   5294 
   5295     /**
   5296      * Set whether the screen capture is disabled for the user managed by the specified admin.
   5297      */
   5298     @Override
   5299     public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
   5300         if (!mHasFeature) {
   5301             return;
   5302         }
   5303         Preconditions.checkNotNull(who, "ComponentName is null");
   5304         final int userHandle = UserHandle.getCallingUserId();
   5305         synchronized (this) {
   5306             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   5307                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5308             if (ap.disableScreenCapture != disabled) {
   5309                 ap.disableScreenCapture = disabled;
   5310                 saveSettingsLocked(userHandle);
   5311                 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
   5312             }
   5313         }
   5314     }
   5315 
   5316     /**
   5317      * Returns whether or not screen capture is disabled for a given admin, or disabled for any
   5318      * active admin (if given admin is null).
   5319      */
   5320     @Override
   5321     public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
   5322         if (!mHasFeature) {
   5323             return false;
   5324         }
   5325         synchronized (this) {
   5326             if (who != null) {
   5327                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   5328                 return (admin != null) ? admin.disableScreenCapture : false;
   5329             }
   5330 
   5331             DevicePolicyData policy = getUserData(userHandle);
   5332             final int N = policy.mAdminList.size();
   5333             for (int i = 0; i < N; i++) {
   5334                 ActiveAdmin admin = policy.mAdminList.get(i);
   5335                 if (admin.disableScreenCapture) {
   5336                     return true;
   5337                 }
   5338             }
   5339             return false;
   5340         }
   5341     }
   5342 
   5343     private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
   5344             final boolean disabled) {
   5345         mHandler.post(new Runnable() {
   5346             @Override
   5347             public void run() {
   5348                 try {
   5349                     mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
   5350                 } catch (RemoteException e) {
   5351                     Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
   5352                 }
   5353             }
   5354         });
   5355     }
   5356 
   5357     /**
   5358      * Set whether auto time is required by the specified admin (must be device owner).
   5359      */
   5360     @Override
   5361     public void setAutoTimeRequired(ComponentName who, boolean required) {
   5362         if (!mHasFeature) {
   5363             return;
   5364         }
   5365         Preconditions.checkNotNull(who, "ComponentName is null");
   5366         final int userHandle = UserHandle.getCallingUserId();
   5367         synchronized (this) {
   5368             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   5369                     DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5370             if (admin.requireAutoTime != required) {
   5371                 admin.requireAutoTime = required;
   5372                 saveSettingsLocked(userHandle);
   5373             }
   5374         }
   5375 
   5376         // Turn AUTO_TIME on in settings if it is required
   5377         if (required) {
   5378             long ident = mInjector.binderClearCallingIdentity();
   5379             try {
   5380                 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
   5381             } finally {
   5382                 mInjector.binderRestoreCallingIdentity(ident);
   5383             }
   5384         }
   5385     }
   5386 
   5387     /**
   5388      * Returns whether or not auto time is required by the device owner.
   5389      */
   5390     @Override
   5391     public boolean getAutoTimeRequired() {
   5392         if (!mHasFeature) {
   5393             return false;
   5394         }
   5395         synchronized (this) {
   5396             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
   5397             return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
   5398         }
   5399     }
   5400 
   5401     @Override
   5402     public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
   5403         if (!mHasFeature) {
   5404             return;
   5405         }
   5406         Preconditions.checkNotNull(who, "ComponentName is null");
   5407         // Allow setting this policy to true only if there is a split system user.
   5408         if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
   5409             throw new UnsupportedOperationException(
   5410                     "Cannot force ephemeral users on systems without split system user.");
   5411         }
   5412         boolean removeAllUsers = false;
   5413         synchronized (this) {
   5414             final ActiveAdmin deviceOwner =
   5415                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5416             if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
   5417                 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
   5418                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   5419                 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
   5420                 removeAllUsers = forceEphemeralUsers;
   5421             }
   5422         }
   5423         if (removeAllUsers) {
   5424             long identitity = mInjector.binderClearCallingIdentity();
   5425             try {
   5426                 mUserManagerInternal.removeAllUsers();
   5427             } finally {
   5428                 mInjector.binderRestoreCallingIdentity(identitity);
   5429             }
   5430         }
   5431     }
   5432 
   5433     @Override
   5434     public boolean getForceEphemeralUsers(ComponentName who) {
   5435         if (!mHasFeature) {
   5436             return false;
   5437         }
   5438         Preconditions.checkNotNull(who, "ComponentName is null");
   5439         synchronized (this) {
   5440             final ActiveAdmin deviceOwner =
   5441                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5442             return deviceOwner.forceEphemeralUsers;
   5443         }
   5444     }
   5445 
   5446     private boolean isDeviceOwnerManagedSingleUserDevice() {
   5447         synchronized (this) {
   5448             if (!mOwners.hasDeviceOwner()) {
   5449                 return false;
   5450             }
   5451         }
   5452         final long callingIdentity = mInjector.binderClearCallingIdentity();
   5453         try {
   5454             if (mInjector.userManagerIsSplitSystemUser()) {
   5455                 // In split system user mode, only allow the case where the device owner is managing
   5456                 // the only non-system user of the device
   5457                 return (mUserManager.getUserCount() == 2
   5458                         && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
   5459             } else  {
   5460                 return mUserManager.getUserCount() == 1;
   5461             }
   5462         } finally {
   5463             mInjector.binderRestoreCallingIdentity(callingIdentity);
   5464         }
   5465     }
   5466 
   5467     private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
   5468         synchronized (this) {
   5469             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5470         }
   5471         if (!isDeviceOwnerManagedSingleUserDevice()) {
   5472             throw new SecurityException(
   5473                     "There should only be one user, managed by Device Owner");
   5474         }
   5475     }
   5476 
   5477     @Override
   5478     public boolean requestBugreport(ComponentName who) {
   5479         if (!mHasFeature) {
   5480             return false;
   5481         }
   5482         Preconditions.checkNotNull(who, "ComponentName is null");
   5483         ensureDeviceOwnerManagingSingleUser(who);
   5484 
   5485         if (mRemoteBugreportServiceIsActive.get()
   5486                 || (getDeviceOwnerRemoteBugreportUri() != null)) {
   5487             Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
   5488             return false;
   5489         }
   5490 
   5491         final long callingIdentity = mInjector.binderClearCallingIdentity();
   5492         try {
   5493             ActivityManagerNative.getDefault().requestBugReport(
   5494                     ActivityManager.BUGREPORT_OPTION_REMOTE);
   5495 
   5496             mRemoteBugreportServiceIsActive.set(true);
   5497             mRemoteBugreportSharingAccepted.set(false);
   5498             registerRemoteBugreportReceivers();
   5499             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
   5500                     RemoteBugreportUtils.buildNotification(mContext,
   5501                             DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
   5502             mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
   5503                     RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
   5504             return true;
   5505         } catch (RemoteException re) {
   5506             // should never happen
   5507             Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
   5508             return false;
   5509         } finally {
   5510             mInjector.binderRestoreCallingIdentity(callingIdentity);
   5511         }
   5512     }
   5513 
   5514     synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
   5515         Intent intent = new Intent(action);
   5516         intent.setComponent(mOwners.getDeviceOwnerComponent());
   5517         if (extras != null) {
   5518             intent.putExtras(extras);
   5519         }
   5520         mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
   5521     }
   5522 
   5523     private synchronized String getDeviceOwnerRemoteBugreportUri() {
   5524         return mOwners.getDeviceOwnerRemoteBugreportUri();
   5525     }
   5526 
   5527     private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
   5528             String bugreportHash) {
   5529         mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
   5530     }
   5531 
   5532     private void registerRemoteBugreportReceivers() {
   5533         try {
   5534             IntentFilter filterFinished = new IntentFilter(
   5535                     DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
   5536                     RemoteBugreportUtils.BUGREPORT_MIMETYPE);
   5537             mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
   5538         } catch (IntentFilter.MalformedMimeTypeException e) {
   5539             // should never happen, as setting a constant
   5540             Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
   5541         }
   5542         IntentFilter filterConsent = new IntentFilter();
   5543         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
   5544         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
   5545         mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
   5546     }
   5547 
   5548     private void onBugreportFinished(Intent intent) {
   5549         mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
   5550         mRemoteBugreportServiceIsActive.set(false);
   5551         Uri bugreportUri = intent.getData();
   5552         String bugreportUriString = null;
   5553         if (bugreportUri != null) {
   5554             bugreportUriString = bugreportUri.toString();
   5555         }
   5556         String bugreportHash = intent.getStringExtra(
   5557                 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
   5558         if (mRemoteBugreportSharingAccepted.get()) {
   5559             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
   5560             mInjector.getNotificationManager().cancel(LOG_TAG,
   5561                     RemoteBugreportUtils.NOTIFICATION_ID);
   5562         } else {
   5563             setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
   5564             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
   5565                     RemoteBugreportUtils.buildNotification(mContext,
   5566                             DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
   5567                             UserHandle.ALL);
   5568         }
   5569         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
   5570     }
   5571 
   5572     private void onBugreportFailed() {
   5573         mRemoteBugreportServiceIsActive.set(false);
   5574         mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
   5575                 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
   5576         mRemoteBugreportSharingAccepted.set(false);
   5577         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
   5578         mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
   5579         Bundle extras = new Bundle();
   5580         extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
   5581                 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
   5582         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
   5583         mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
   5584         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
   5585     }
   5586 
   5587     private void onBugreportSharingAccepted() {
   5588         mRemoteBugreportSharingAccepted.set(true);
   5589         String bugreportUriString = null;
   5590         String bugreportHash = null;
   5591         synchronized (this) {
   5592             bugreportUriString = getDeviceOwnerRemoteBugreportUri();
   5593             bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
   5594         }
   5595         if (bugreportUriString != null) {
   5596             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
   5597         } else if (mRemoteBugreportServiceIsActive.get()) {
   5598             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
   5599                     RemoteBugreportUtils.buildNotification(mContext,
   5600                             DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
   5601                             UserHandle.ALL);
   5602         }
   5603     }
   5604 
   5605     private void onBugreportSharingDeclined() {
   5606         if (mRemoteBugreportServiceIsActive.get()) {
   5607             mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
   5608                     RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
   5609             mRemoteBugreportServiceIsActive.set(false);
   5610             mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
   5611             mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
   5612         }
   5613         mRemoteBugreportSharingAccepted.set(false);
   5614         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
   5615         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
   5616     }
   5617 
   5618     private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
   5619             String bugreportHash) {
   5620         ParcelFileDescriptor pfd = null;
   5621         try {
   5622             if (bugreportUriString == null) {
   5623                 throw new FileNotFoundException();
   5624             }
   5625             Uri bugreportUri = Uri.parse(bugreportUriString);
   5626             pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
   5627 
   5628             synchronized (this) {
   5629                 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
   5630                 intent.setComponent(mOwners.getDeviceOwnerComponent());
   5631                 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
   5632                 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
   5633                 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
   5634                         bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
   5635                 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
   5636             }
   5637         } catch (FileNotFoundException e) {
   5638             Bundle extras = new Bundle();
   5639             extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
   5640                     DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
   5641             sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
   5642         } finally {
   5643             try {
   5644                 if (pfd != null) {
   5645                     pfd.close();
   5646                 }
   5647             } catch (IOException ex) {
   5648                 // Ignore
   5649             }
   5650             mRemoteBugreportSharingAccepted.set(false);
   5651             setDeviceOwnerRemoteBugreportUriAndHash(null, null);
   5652         }
   5653     }
   5654 
   5655     /**
   5656      * Disables all device cameras according to the specified admin.
   5657      */
   5658     @Override
   5659     public void setCameraDisabled(ComponentName who, boolean disabled) {
   5660         if (!mHasFeature) {
   5661             return;
   5662         }
   5663         Preconditions.checkNotNull(who, "ComponentName is null");
   5664         final int userHandle = mInjector.userHandleGetCallingUserId();
   5665         synchronized (this) {
   5666             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   5667                     DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
   5668             if (ap.disableCamera != disabled) {
   5669                 ap.disableCamera = disabled;
   5670                 saveSettingsLocked(userHandle);
   5671             }
   5672         }
   5673         // Tell the user manager that the restrictions have changed.
   5674         pushUserRestrictions(userHandle);
   5675     }
   5676 
   5677     /**
   5678      * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
   5679      * active admins.
   5680      */
   5681     @Override
   5682     public boolean getCameraDisabled(ComponentName who, int userHandle) {
   5683         return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
   5684     }
   5685 
   5686     private boolean getCameraDisabled(ComponentName who, int userHandle,
   5687             boolean mergeDeviceOwnerRestriction) {
   5688         if (!mHasFeature) {
   5689             return false;
   5690         }
   5691         synchronized (this) {
   5692             if (who != null) {
   5693                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   5694                 return (admin != null) ? admin.disableCamera : false;
   5695             }
   5696             // First, see if DO has set it.  If so, it's device-wide.
   5697             if (mergeDeviceOwnerRestriction) {
   5698                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
   5699                 if (deviceOwner != null && deviceOwner.disableCamera) {
   5700                     return true;
   5701                 }
   5702             }
   5703 
   5704             // Then check each device admin on the user.
   5705             DevicePolicyData policy = getUserData(userHandle);
   5706             // Determine whether or not the device camera is disabled for any active admins.
   5707             final int N = policy.mAdminList.size();
   5708             for (int i = 0; i < N; i++) {
   5709                 ActiveAdmin admin = policy.mAdminList.get(i);
   5710                 if (admin.disableCamera) {
   5711                     return true;
   5712                 }
   5713             }
   5714             return false;
   5715         }
   5716     }
   5717 
   5718     @Override
   5719     public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
   5720         if (!mHasFeature) {
   5721             return;
   5722         }
   5723         Preconditions.checkNotNull(who, "ComponentName is null");
   5724         final int userHandle = mInjector.userHandleGetCallingUserId();
   5725         if (isManagedProfile(userHandle)) {
   5726             if (parent) {
   5727                 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
   5728             } else {
   5729                 which = which & PROFILE_KEYGUARD_FEATURES;
   5730             }
   5731         }
   5732         synchronized (this) {
   5733             ActiveAdmin ap = getActiveAdminForCallerLocked(
   5734                     who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
   5735             if (ap.disabledKeyguardFeatures != which) {
   5736                 ap.disabledKeyguardFeatures = which;
   5737                 saveSettingsLocked(userHandle);
   5738             }
   5739         }
   5740     }
   5741 
   5742     /**
   5743      * Gets the disabled state for features in keyguard for the given admin,
   5744      * or the aggregate of all active admins if who is null.
   5745      */
   5746     @Override
   5747     public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
   5748         if (!mHasFeature) {
   5749             return 0;
   5750         }
   5751         enforceFullCrossUsersPermission(userHandle);
   5752         final long ident = mInjector.binderClearCallingIdentity();
   5753         try {
   5754             synchronized (this) {
   5755                 if (who != null) {
   5756                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
   5757                     return (admin != null) ? admin.disabledKeyguardFeatures : 0;
   5758                 }
   5759 
   5760                 final List<ActiveAdmin> admins;
   5761                 if (!parent && isManagedProfile(userHandle)) {
   5762                     // If we are being asked about a managed profile, just return keyguard features
   5763                     // disabled by admins in the profile.
   5764                     admins = getUserDataUnchecked(userHandle).mAdminList;
   5765                 } else {
   5766                     // Otherwise return those set by admins in the user and its profiles.
   5767                     admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   5768                 }
   5769 
   5770                 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
   5771                 final int N = admins.size();
   5772                 for (int i = 0; i < N; i++) {
   5773                     ActiveAdmin admin = admins.get(i);
   5774                     int userId = admin.getUserHandle().getIdentifier();
   5775                     boolean isRequestedUser = !parent && (userId == userHandle);
   5776                     if (isRequestedUser || !isManagedProfile(userId)) {
   5777                         // If we are being asked explicitly about this user
   5778                         // return all disabled features even if its a managed profile.
   5779                         which |= admin.disabledKeyguardFeatures;
   5780                     } else {
   5781                         // Otherwise a managed profile is only allowed to disable
   5782                         // some features on the parent user.
   5783                         which |= (admin.disabledKeyguardFeatures
   5784                                 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
   5785                     }
   5786                 }
   5787                 return which;
   5788             }
   5789         } finally {
   5790             mInjector.binderRestoreCallingIdentity(ident);
   5791         }
   5792     }
   5793 
   5794     @Override
   5795     public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
   5796         if (!mHasFeature) {
   5797             return;
   5798         }
   5799         Preconditions.checkNotNull(who, "ComponentName is null");
   5800         Preconditions.checkNotNull(packageList, "packageList is null");
   5801         final int userHandle = UserHandle.getCallingUserId();
   5802         synchronized (this) {
   5803             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   5804                     DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5805             admin.keepUninstalledPackages = packageList;
   5806             saveSettingsLocked(userHandle);
   5807             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
   5808         }
   5809     }
   5810 
   5811     @Override
   5812     public List<String> getKeepUninstalledPackages(ComponentName who) {
   5813         Preconditions.checkNotNull(who, "ComponentName is null");
   5814         if (!mHasFeature) {
   5815             return null;
   5816         }
   5817         // TODO In split system user mode, allow apps on user 0 to query the list
   5818         synchronized (this) {
   5819             // Check if this is the device owner who is calling
   5820             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5821             return getKeepUninstalledPackagesLocked();
   5822         }
   5823     }
   5824 
   5825     private List<String> getKeepUninstalledPackagesLocked() {
   5826         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
   5827         return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
   5828     }
   5829 
   5830     @Override
   5831     public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
   5832         if (!mHasFeature) {
   5833             return false;
   5834         }
   5835         if (admin == null
   5836                 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
   5837             throw new IllegalArgumentException("Invalid component " + admin
   5838                     + " for device owner");
   5839         }
   5840         synchronized (this) {
   5841             enforceCanSetDeviceOwnerLocked(admin, userId);
   5842             if (getActiveAdminUncheckedLocked(admin, userId) == null
   5843                     || getUserData(userId).mRemovingAdmins.contains(admin)) {
   5844                 throw new IllegalArgumentException("Not active admin: " + admin);
   5845             }
   5846 
   5847             // Shutting down backup manager service permanently.
   5848             long ident = mInjector.binderClearCallingIdentity();
   5849             try {
   5850                 if (mInjector.getIBackupManager() != null) {
   5851                     mInjector.getIBackupManager()
   5852                             .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
   5853                 }
   5854             } catch (RemoteException e) {
   5855                 throw new IllegalStateException("Failed deactivating backup service.", e);
   5856             } finally {
   5857                 mInjector.binderRestoreCallingIdentity(ident);
   5858             }
   5859 
   5860             mOwners.setDeviceOwner(admin, ownerName, userId);
   5861             mOwners.writeDeviceOwner();
   5862             updateDeviceOwnerLocked();
   5863             setDeviceOwnerSystemPropertyLocked();
   5864             Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
   5865 
   5866             ident = mInjector.binderClearCallingIdentity();
   5867             try {
   5868                 // TODO Send to system too?
   5869                 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
   5870             } finally {
   5871                 mInjector.binderRestoreCallingIdentity(ident);
   5872             }
   5873             Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
   5874             return true;
   5875         }
   5876     }
   5877 
   5878     public boolean isDeviceOwner(ComponentName who, int userId) {
   5879         synchronized (this) {
   5880             return mOwners.hasDeviceOwner()
   5881                     && mOwners.getDeviceOwnerUserId() == userId
   5882                     && mOwners.getDeviceOwnerComponent().equals(who);
   5883         }
   5884     }
   5885 
   5886     public boolean isProfileOwner(ComponentName who, int userId) {
   5887         final ComponentName profileOwner = getProfileOwner(userId);
   5888         return who != null && who.equals(profileOwner);
   5889     }
   5890 
   5891     @Override
   5892     public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
   5893         if (!mHasFeature) {
   5894             return null;
   5895         }
   5896         if (!callingUserOnly) {
   5897             enforceManageUsers();
   5898         }
   5899         synchronized (this) {
   5900             if (!mOwners.hasDeviceOwner()) {
   5901                 return null;
   5902             }
   5903             if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
   5904                     mOwners.getDeviceOwnerUserId()) {
   5905                 return null;
   5906             }
   5907             return mOwners.getDeviceOwnerComponent();
   5908         }
   5909     }
   5910 
   5911     @Override
   5912     public int getDeviceOwnerUserId() {
   5913         if (!mHasFeature) {
   5914             return UserHandle.USER_NULL;
   5915         }
   5916         enforceManageUsers();
   5917         synchronized (this) {
   5918             return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
   5919         }
   5920     }
   5921 
   5922     /**
   5923      * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
   5924      * MANAGE_USERS.
   5925      */
   5926     @Override
   5927     public String getDeviceOwnerName() {
   5928         if (!mHasFeature) {
   5929             return null;
   5930         }
   5931         enforceManageUsers();
   5932         synchronized (this) {
   5933             if (!mOwners.hasDeviceOwner()) {
   5934                 return null;
   5935             }
   5936             // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
   5937             // Should setDeviceOwner/ProfileOwner still take a name?
   5938             String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
   5939             return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
   5940         }
   5941     }
   5942 
   5943     // Returns the active device owner or null if there is no device owner.
   5944     @VisibleForTesting
   5945     ActiveAdmin getDeviceOwnerAdminLocked() {
   5946         ComponentName component = mOwners.getDeviceOwnerComponent();
   5947         if (component == null) {
   5948             return null;
   5949         }
   5950 
   5951         DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
   5952         final int n = policy.mAdminList.size();
   5953         for (int i = 0; i < n; i++) {
   5954             ActiveAdmin admin = policy.mAdminList.get(i);
   5955             if (component.equals(admin.info.getComponent())) {
   5956                 return admin;
   5957             }
   5958         }
   5959         Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
   5960         return null;
   5961     }
   5962 
   5963     @Override
   5964     public void clearDeviceOwner(String packageName) {
   5965         Preconditions.checkNotNull(packageName, "packageName is null");
   5966         final int callingUid = mInjector.binderGetCallingUid();
   5967         try {
   5968             int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
   5969                     UserHandle.getUserId(callingUid));
   5970             if (uid != callingUid) {
   5971                 throw new SecurityException("Invalid packageName");
   5972             }
   5973         } catch (NameNotFoundException e) {
   5974             throw new SecurityException(e);
   5975         }
   5976         synchronized (this) {
   5977             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
   5978             final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
   5979             if (!mOwners.hasDeviceOwner()
   5980                     || !deviceOwnerComponent.getPackageName().equals(packageName)
   5981                     || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
   5982                 throw new SecurityException(
   5983                         "clearDeviceOwner can only be called by the device owner");
   5984             }
   5985             enforceUserUnlocked(deviceOwnerUserId);
   5986 
   5987             final ActiveAdmin admin = getDeviceOwnerAdminLocked();
   5988             long ident = mInjector.binderClearCallingIdentity();
   5989             try {
   5990                 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
   5991                 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
   5992             } finally {
   5993                 mInjector.binderRestoreCallingIdentity(ident);
   5994             }
   5995             Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
   5996         }
   5997     }
   5998 
   5999     private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
   6000         if (admin != null) {
   6001             admin.disableCamera = false;
   6002             admin.userRestrictions = null;
   6003             admin.forceEphemeralUsers = false;
   6004             mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
   6005         }
   6006         clearUserPoliciesLocked(userId);
   6007 
   6008         mOwners.clearDeviceOwner();
   6009         mOwners.writeDeviceOwner();
   6010         updateDeviceOwnerLocked();
   6011         disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
   6012         try {
   6013             // Reactivate backup service.
   6014             mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
   6015         } catch (RemoteException e) {
   6016             throw new IllegalStateException("Failed reactivating backup service.", e);
   6017         }
   6018     }
   6019 
   6020     @Override
   6021     public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
   6022         if (!mHasFeature) {
   6023             return false;
   6024         }
   6025         if (who == null
   6026                 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
   6027             throw new IllegalArgumentException("Component " + who
   6028                     + " not installed for userId:" + userHandle);
   6029         }
   6030         synchronized (this) {
   6031             enforceCanSetProfileOwnerLocked(who, userHandle);
   6032 
   6033             if (getActiveAdminUncheckedLocked(who, userHandle) == null
   6034                     || getUserData(userHandle).mRemovingAdmins.contains(who)) {
   6035                 throw new IllegalArgumentException("Not active admin: " + who);
   6036             }
   6037 
   6038             mOwners.setProfileOwner(who, ownerName, userHandle);
   6039             mOwners.writeProfileOwner(userHandle);
   6040             Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
   6041             return true;
   6042         }
   6043     }
   6044 
   6045     @Override
   6046     public void clearProfileOwner(ComponentName who) {
   6047         if (!mHasFeature) {
   6048             return;
   6049         }
   6050         final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
   6051         final int userId = callingUser.getIdentifier();
   6052         enforceNotManagedProfile(userId, "clear profile owner");
   6053         enforceUserUnlocked(userId);
   6054         // Check if this is the profile owner who is calling
   6055         final ActiveAdmin admin =
   6056                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6057         synchronized (this) {
   6058             final long ident = mInjector.binderClearCallingIdentity();
   6059             try {
   6060                 clearProfileOwnerLocked(admin, userId);
   6061                 removeActiveAdminLocked(who, userId);
   6062             } finally {
   6063                 mInjector.binderRestoreCallingIdentity(ident);
   6064             }
   6065             Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
   6066         }
   6067     }
   6068 
   6069     public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
   6070         if (admin != null) {
   6071             admin.disableCamera = false;
   6072             admin.userRestrictions = null;
   6073         }
   6074         clearUserPoliciesLocked(userId);
   6075         mOwners.removeProfileOwner(userId);
   6076         mOwners.writeProfileOwner(userId);
   6077     }
   6078 
   6079     @Override
   6080     public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
   6081         Preconditions.checkNotNull(who, "ComponentName is null");
   6082         if (!mHasFeature) {
   6083             return;
   6084         }
   6085 
   6086         synchronized (this) {
   6087             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   6088             long token = mInjector.binderClearCallingIdentity();
   6089             try {
   6090                 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
   6091             } finally {
   6092                 mInjector.binderRestoreCallingIdentity(token);
   6093             }
   6094         }
   6095     }
   6096 
   6097     @Override
   6098     public CharSequence getDeviceOwnerLockScreenInfo() {
   6099         return mLockPatternUtils.getDeviceOwnerInfo();
   6100     }
   6101 
   6102     private void clearUserPoliciesLocked(int userId) {
   6103         // Reset some of the user-specific policies
   6104         DevicePolicyData policy = getUserData(userId);
   6105         policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
   6106         policy.mDelegatedCertInstallerPackage = null;
   6107         policy.mApplicationRestrictionsManagingPackage = null;
   6108         policy.mStatusBarDisabled = false;
   6109         policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
   6110         saveSettingsLocked(userId);
   6111 
   6112         try {
   6113             mIPackageManager.updatePermissionFlagsForAllApps(
   6114                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
   6115                     0  /* flagValues */, userId);
   6116             pushUserRestrictions(userId);
   6117         } catch (RemoteException re) {
   6118             // Shouldn't happen.
   6119         }
   6120     }
   6121 
   6122     @Override
   6123     public boolean hasUserSetupCompleted() {
   6124         return hasUserSetupCompleted(UserHandle.getCallingUserId());
   6125     }
   6126 
   6127     private boolean hasUserSetupCompleted(int userHandle) {
   6128         if (!mHasFeature) {
   6129             return true;
   6130         }
   6131         return getUserData(userHandle).mUserSetupComplete;
   6132     }
   6133 
   6134     @Override
   6135     public int getUserProvisioningState() {
   6136         if (!mHasFeature) {
   6137             return DevicePolicyManager.STATE_USER_UNMANAGED;
   6138         }
   6139         int userHandle = mInjector.userHandleGetCallingUserId();
   6140         return getUserProvisioningState(userHandle);
   6141     }
   6142 
   6143     private int getUserProvisioningState(int userHandle) {
   6144         return getUserData(userHandle).mUserProvisioningState;
   6145     }
   6146 
   6147     @Override
   6148     public void setUserProvisioningState(int newState, int userHandle) {
   6149         if (!mHasFeature) {
   6150             return;
   6151         }
   6152 
   6153         if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
   6154                 && getManagedUserId(userHandle) == -1) {
   6155             // No managed device, user or profile, so setting provisioning state makes no sense.
   6156             throw new IllegalStateException("Not allowed to change provisioning state unless a "
   6157                       + "device or profile owner is set.");
   6158         }
   6159 
   6160         synchronized (this) {
   6161             boolean transitionCheckNeeded = true;
   6162 
   6163             // Calling identity/permission checks.
   6164             final int callingUid = mInjector.binderGetCallingUid();
   6165             if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
   6166                 // ADB shell can only move directly from un-managed to finalized as part of directly
   6167                 // setting profile-owner or device-owner.
   6168                 if (getUserProvisioningState(userHandle) !=
   6169                         DevicePolicyManager.STATE_USER_UNMANAGED
   6170                         || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
   6171                     throw new IllegalStateException("Not allowed to change provisioning state "
   6172                             + "unless current provisioning state is unmanaged, and new state is "
   6173                             + "finalized.");
   6174                 }
   6175                 transitionCheckNeeded = false;
   6176             } else {
   6177                 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
   6178                 enforceCanManageProfileAndDeviceOwners();
   6179             }
   6180 
   6181             final DevicePolicyData policyData = getUserData(userHandle);
   6182             if (transitionCheckNeeded) {
   6183                 // Optional state transition check for non-ADB case.
   6184                 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
   6185             }
   6186             policyData.mUserProvisioningState = newState;
   6187             saveSettingsLocked(userHandle);
   6188         }
   6189     }
   6190 
   6191     private void checkUserProvisioningStateTransition(int currentState, int newState) {
   6192         // Valid transitions for normal use-cases.
   6193         switch (currentState) {
   6194             case DevicePolicyManager.STATE_USER_UNMANAGED:
   6195                 // Can move to any state from unmanaged (except itself as an edge case)..
   6196                 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
   6197                     return;
   6198                 }
   6199                 break;
   6200             case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
   6201             case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
   6202                 // Can only move to finalized from these states.
   6203                 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
   6204                     return;
   6205                 }
   6206                 break;
   6207             case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
   6208                 // Current user has a managed-profile, but current user is not managed, so
   6209                 // rather than moving to finalized state, go back to unmanaged once
   6210                 // profile provisioning is complete.
   6211                 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
   6212                     return;
   6213                 }
   6214                 break;
   6215             case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
   6216                 // Cannot transition out of finalized.
   6217                 break;
   6218         }
   6219 
   6220         // Didn't meet any of the accepted state transition checks above, throw appropriate error.
   6221         throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
   6222                 + "from state [" + currentState + "]");
   6223     }
   6224 
   6225     @Override
   6226     public void setProfileEnabled(ComponentName who) {
   6227         if (!mHasFeature) {
   6228             return;
   6229         }
   6230         Preconditions.checkNotNull(who, "ComponentName is null");
   6231         synchronized (this) {
   6232             // Check if this is the profile owner who is calling
   6233             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6234             final int userId = UserHandle.getCallingUserId();
   6235             enforceManagedProfile(userId, "enable the profile");
   6236 
   6237             long id = mInjector.binderClearCallingIdentity();
   6238             try {
   6239                 mUserManager.setUserEnabled(userId);
   6240                 UserInfo parent = mUserManager.getProfileParent(userId);
   6241                 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
   6242                 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
   6243                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
   6244                         Intent.FLAG_RECEIVER_FOREGROUND);
   6245                 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
   6246             } finally {
   6247                 mInjector.binderRestoreCallingIdentity(id);
   6248             }
   6249         }
   6250     }
   6251 
   6252     @Override
   6253     public void setProfileName(ComponentName who, String profileName) {
   6254         Preconditions.checkNotNull(who, "ComponentName is null");
   6255         int userId = UserHandle.getCallingUserId();
   6256         // Check if this is the profile owner (includes device owner).
   6257         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6258 
   6259         long id = mInjector.binderClearCallingIdentity();
   6260         try {
   6261             mUserManager.setUserName(userId, profileName);
   6262         } finally {
   6263             mInjector.binderRestoreCallingIdentity(id);
   6264         }
   6265     }
   6266 
   6267     @Override
   6268     public ComponentName getProfileOwner(int userHandle) {
   6269         if (!mHasFeature) {
   6270             return null;
   6271         }
   6272 
   6273         synchronized (this) {
   6274             return mOwners.getProfileOwnerComponent(userHandle);
   6275         }
   6276     }
   6277 
   6278     // Returns the active profile owner for this user or null if the current user has no
   6279     // profile owner.
   6280     @VisibleForTesting
   6281     ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
   6282         ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
   6283         if (profileOwner == null) {
   6284             return null;
   6285         }
   6286         DevicePolicyData policy = getUserData(userHandle);
   6287         final int n = policy.mAdminList.size();
   6288         for (int i = 0; i < n; i++) {
   6289             ActiveAdmin admin = policy.mAdminList.get(i);
   6290             if (profileOwner.equals(admin.info.getComponent())) {
   6291                 return admin;
   6292             }
   6293         }
   6294         return null;
   6295     }
   6296 
   6297     @Override
   6298     public String getProfileOwnerName(int userHandle) {
   6299         if (!mHasFeature) {
   6300             return null;
   6301         }
   6302         enforceManageUsers();
   6303         ComponentName profileOwner = getProfileOwner(userHandle);
   6304         if (profileOwner == null) {
   6305             return null;
   6306         }
   6307         return getApplicationLabel(profileOwner.getPackageName(), userHandle);
   6308     }
   6309 
   6310     /**
   6311      * Canonical name for a given package.
   6312      */
   6313     private String getApplicationLabel(String packageName, int userHandle) {
   6314         long token = mInjector.binderClearCallingIdentity();
   6315         try {
   6316             final Context userContext;
   6317             try {
   6318                 UserHandle handle = new UserHandle(userHandle);
   6319                 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
   6320             } catch (PackageManager.NameNotFoundException nnfe) {
   6321                 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
   6322                 return null;
   6323             }
   6324             ApplicationInfo appInfo = userContext.getApplicationInfo();
   6325             CharSequence result = null;
   6326             if (appInfo != null) {
   6327                 PackageManager pm = userContext.getPackageManager();
   6328                 result = pm.getApplicationLabel(appInfo);
   6329             }
   6330             return result != null ? result.toString() : null;
   6331         } finally {
   6332             mInjector.binderRestoreCallingIdentity(token);
   6333         }
   6334     }
   6335 
   6336     /**
   6337      * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
   6338      * permission.
   6339      * The profile owner can only be set before the user setup phase has completed,
   6340      * except for:
   6341      * - SYSTEM_UID
   6342      * - adb if there are no accounts. (But see {@link #hasIncompatibleAccountsLocked})
   6343      */
   6344     private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle) {
   6345         UserInfo info = getUserInfo(userHandle);
   6346         if (info == null) {
   6347             // User doesn't exist.
   6348             throw new IllegalArgumentException(
   6349                     "Attempted to set profile owner for invalid userId: " + userHandle);
   6350         }
   6351         if (info.isGuest()) {
   6352             throw new IllegalStateException("Cannot set a profile owner on a guest");
   6353         }
   6354         if (mOwners.hasProfileOwner(userHandle)) {
   6355             throw new IllegalStateException("Trying to set the profile owner, but profile owner "
   6356                     + "is already set.");
   6357         }
   6358         if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
   6359             throw new IllegalStateException("Trying to set the profile owner, but the user "
   6360                     + "already has a device owner.");
   6361         }
   6362         int callingUid = mInjector.binderGetCallingUid();
   6363         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
   6364             if (hasUserSetupCompleted(userHandle)
   6365                     && hasIncompatibleAccountsLocked(userHandle, owner)) {
   6366                 throw new IllegalStateException("Not allowed to set the profile owner because "
   6367                         + "there are already some accounts on the profile");
   6368             }
   6369             return;
   6370         }
   6371         enforceCanManageProfileAndDeviceOwners();
   6372         if (hasUserSetupCompleted(userHandle) && !isCallerWithSystemUid()) {
   6373             throw new IllegalStateException("Cannot set the profile owner on a user which is "
   6374                     + "already set-up");
   6375         }
   6376     }
   6377 
   6378     /**
   6379      * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
   6380      * permission.
   6381      */
   6382     private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId) {
   6383         int callingUid = mInjector.binderGetCallingUid();
   6384         boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
   6385         if (!isAdb) {
   6386             enforceCanManageProfileAndDeviceOwners();
   6387         }
   6388 
   6389         final int code = checkSetDeviceOwnerPreConditionLocked(owner, userId, isAdb);
   6390         switch (code) {
   6391             case CODE_OK:
   6392                 return;
   6393             case CODE_HAS_DEVICE_OWNER:
   6394                 throw new IllegalStateException(
   6395                         "Trying to set the device owner, but device owner is already set.");
   6396             case CODE_USER_HAS_PROFILE_OWNER:
   6397                 throw new IllegalStateException("Trying to set the device owner, but the user "
   6398                         + "already has a profile owner.");
   6399             case CODE_USER_NOT_RUNNING:
   6400                 throw new IllegalStateException("User not running: " + userId);
   6401             case CODE_NOT_SYSTEM_USER:
   6402                 throw new IllegalStateException("User is not system user");
   6403             case CODE_USER_SETUP_COMPLETED:
   6404                 throw new IllegalStateException(
   6405                         "Cannot set the device owner if the device is already set-up");
   6406             case CODE_NONSYSTEM_USER_EXISTS:
   6407                 throw new IllegalStateException("Not allowed to set the device owner because there "
   6408                         + "are already several users on the device");
   6409             case CODE_ACCOUNTS_NOT_EMPTY:
   6410                 throw new IllegalStateException("Not allowed to set the device owner because there "
   6411                         + "are already some accounts on the device");
   6412             default:
   6413                 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
   6414         }
   6415     }
   6416 
   6417     private void enforceUserUnlocked(int userId) {
   6418         // Since we're doing this operation on behalf of an app, we only
   6419         // want to use the actual "unlocked" state.
   6420         Preconditions.checkState(mUserManager.isUserUnlocked(userId),
   6421                 "User must be running and unlocked");
   6422     }
   6423 
   6424     private void enforceManageUsers() {
   6425         final int callingUid = mInjector.binderGetCallingUid();
   6426         if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
   6427             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
   6428         }
   6429     }
   6430 
   6431     private void enforceFullCrossUsersPermission(int userHandle) {
   6432         enforceSystemUserOrPermission(userHandle,
   6433                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
   6434     }
   6435 
   6436     private void enforceCrossUsersPermission(int userHandle) {
   6437         enforceSystemUserOrPermission(userHandle,
   6438                 android.Manifest.permission.INTERACT_ACROSS_USERS);
   6439     }
   6440 
   6441     private void enforceSystemUserOrPermission(int userHandle, String permission) {
   6442         if (userHandle < 0) {
   6443             throw new IllegalArgumentException("Invalid userId " + userHandle);
   6444         }
   6445         final int callingUid = mInjector.binderGetCallingUid();
   6446         if (userHandle == UserHandle.getUserId(callingUid)) {
   6447             return;
   6448         }
   6449         if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
   6450             mContext.enforceCallingOrSelfPermission(permission,
   6451                     "Must be system or have " + permission + " permission");
   6452         }
   6453     }
   6454 
   6455     private void enforceManagedProfile(int userHandle, String message) {
   6456         if(!isManagedProfile(userHandle)) {
   6457             throw new SecurityException("You can not " + message + " outside a managed profile.");
   6458         }
   6459     }
   6460 
   6461     private void enforceNotManagedProfile(int userHandle, String message) {
   6462         if(isManagedProfile(userHandle)) {
   6463             throw new SecurityException("You can not " + message + " for a managed profile.");
   6464         }
   6465     }
   6466 
   6467     private void ensureCallerPackage(@Nullable String packageName) {
   6468         if (packageName == null) {
   6469             Preconditions.checkState(isCallerWithSystemUid(),
   6470                     "Only caller can omit package name");
   6471         } else {
   6472             final int callingUid = mInjector.binderGetCallingUid();
   6473             final int userId = mInjector.userHandleGetCallingUserId();
   6474             try {
   6475                 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
   6476                         packageName, 0, userId);
   6477                 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
   6478             } catch (RemoteException e) {
   6479                 // Shouldn't happen
   6480             }
   6481         }
   6482     }
   6483 
   6484     private boolean isCallerWithSystemUid() {
   6485         return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
   6486     }
   6487 
   6488     private int getProfileParentId(int userHandle) {
   6489         final long ident = mInjector.binderClearCallingIdentity();
   6490         try {
   6491             UserInfo parentUser = mUserManager.getProfileParent(userHandle);
   6492             return parentUser != null ? parentUser.id : userHandle;
   6493         } finally {
   6494             mInjector.binderRestoreCallingIdentity(ident);
   6495         }
   6496     }
   6497 
   6498     private int getCredentialOwner(int userHandle, boolean parent) {
   6499         final long ident = mInjector.binderClearCallingIdentity();
   6500         try {
   6501             if (parent) {
   6502                 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
   6503                 if (parentProfile != null) {
   6504                     userHandle = parentProfile.id;
   6505                 }
   6506             }
   6507             return mUserManager.getCredentialOwnerProfile(userHandle);
   6508         } finally {
   6509             mInjector.binderRestoreCallingIdentity(ident);
   6510         }
   6511     }
   6512 
   6513     private boolean isManagedProfile(int userHandle) {
   6514         return getUserInfo(userHandle).isManagedProfile();
   6515     }
   6516 
   6517     private void enableIfNecessary(String packageName, int userId) {
   6518         try {
   6519             ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
   6520                     PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
   6521                     userId);
   6522             if (ai.enabledSetting
   6523                     == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
   6524                 mIPackageManager.setApplicationEnabledSetting(packageName,
   6525                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
   6526                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
   6527             }
   6528         } catch (RemoteException e) {
   6529         }
   6530     }
   6531 
   6532     @Override
   6533     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   6534         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
   6535                 != PackageManager.PERMISSION_GRANTED) {
   6536 
   6537             pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
   6538                     + mInjector.binderGetCallingPid()
   6539                     + ", uid=" + mInjector.binderGetCallingUid());
   6540             return;
   6541         }
   6542 
   6543         synchronized (this) {
   6544             pw.println("Current Device Policy Manager state:");
   6545             mOwners.dump("  ", pw);
   6546             int userCount = mUserData.size();
   6547             for (int u = 0; u < userCount; u++) {
   6548                 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
   6549                 pw.println();
   6550                 pw.println("  Enabled Device Admins (User " + policy.mUserHandle
   6551                         + ", provisioningState: " + policy.mUserProvisioningState + "):");
   6552                 final int N = policy.mAdminList.size();
   6553                 for (int i=0; i<N; i++) {
   6554                     ActiveAdmin ap = policy.mAdminList.get(i);
   6555                     if (ap != null) {
   6556                         pw.print("    "); pw.print(ap.info.getComponent().flattenToShortString());
   6557                                 pw.println(":");
   6558                         ap.dump("      ", pw);
   6559                     }
   6560                 }
   6561                 if (!policy.mRemovingAdmins.isEmpty()) {
   6562                     pw.println("    Removing Device Admins (User " + policy.mUserHandle + "): "
   6563                             + policy.mRemovingAdmins);
   6564                 }
   6565 
   6566                 pw.println(" ");
   6567                 pw.print("    mPasswordOwner="); pw.println(policy.mPasswordOwner);
   6568             }
   6569             pw.println();
   6570             pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
   6571         }
   6572     }
   6573 
   6574     private String getEncryptionStatusName(int encryptionStatus) {
   6575         switch (encryptionStatus) {
   6576             case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
   6577                 return "inactive";
   6578             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
   6579                 return "block default key";
   6580             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
   6581                 return "block";
   6582             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
   6583                 return "per-user";
   6584             case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
   6585                 return "unsupported";
   6586             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
   6587                 return "activating";
   6588             default:
   6589                 return "unknown";
   6590         }
   6591     }
   6592 
   6593     @Override
   6594     public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
   6595             ComponentName activity) {
   6596         Preconditions.checkNotNull(who, "ComponentName is null");
   6597         final int userHandle = UserHandle.getCallingUserId();
   6598         synchronized (this) {
   6599             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6600 
   6601             long id = mInjector.binderClearCallingIdentity();
   6602             try {
   6603                 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
   6604             } catch (RemoteException re) {
   6605                 // Shouldn't happen
   6606             } finally {
   6607                 mInjector.binderRestoreCallingIdentity(id);
   6608             }
   6609         }
   6610     }
   6611 
   6612     @Override
   6613     public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
   6614         Preconditions.checkNotNull(who, "ComponentName is null");
   6615         final int userHandle = UserHandle.getCallingUserId();
   6616         synchronized (this) {
   6617             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6618 
   6619             long id = mInjector.binderClearCallingIdentity();
   6620             try {
   6621                 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
   6622             } catch (RemoteException re) {
   6623                 // Shouldn't happen
   6624             } finally {
   6625                 mInjector.binderRestoreCallingIdentity(id);
   6626             }
   6627         }
   6628     }
   6629 
   6630     @Override
   6631     public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
   6632             String packageName) {
   6633         Preconditions.checkNotNull(admin, "ComponentName is null");
   6634 
   6635         final int userHandle = mInjector.userHandleGetCallingUserId();
   6636         synchronized (this) {
   6637             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6638             if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
   6639                 return false;
   6640             }
   6641             DevicePolicyData policy = getUserData(userHandle);
   6642             policy.mApplicationRestrictionsManagingPackage = packageName;
   6643             saveSettingsLocked(userHandle);
   6644             return true;
   6645         }
   6646     }
   6647 
   6648     @Override
   6649     public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
   6650         Preconditions.checkNotNull(admin, "ComponentName is null");
   6651 
   6652         final int userHandle = mInjector.userHandleGetCallingUserId();
   6653         synchronized (this) {
   6654             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6655             DevicePolicyData policy = getUserData(userHandle);
   6656             return policy.mApplicationRestrictionsManagingPackage;
   6657         }
   6658     }
   6659 
   6660     @Override
   6661     public boolean isCallerApplicationRestrictionsManagingPackage() {
   6662         final int callingUid = mInjector.binderGetCallingUid();
   6663         final int userHandle = UserHandle.getUserId(callingUid);
   6664         synchronized (this) {
   6665             final DevicePolicyData policy = getUserData(userHandle);
   6666             if (policy.mApplicationRestrictionsManagingPackage == null) {
   6667                 return false;
   6668             }
   6669 
   6670             try {
   6671                 int uid = mContext.getPackageManager().getPackageUidAsUser(
   6672                         policy.mApplicationRestrictionsManagingPackage, userHandle);
   6673                 return uid == callingUid;
   6674             } catch (NameNotFoundException e) {
   6675                 return false;
   6676             }
   6677         }
   6678     }
   6679 
   6680     private void enforceCanManageApplicationRestrictions(ComponentName who) {
   6681         if (who != null) {
   6682             synchronized (this) {
   6683                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6684             }
   6685         } else if (!isCallerApplicationRestrictionsManagingPackage()) {
   6686             throw new SecurityException(
   6687                     "No admin component given, and caller cannot manage application restrictions "
   6688                     + "for other apps.");
   6689         }
   6690     }
   6691 
   6692     @Override
   6693     public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
   6694         enforceCanManageApplicationRestrictions(who);
   6695 
   6696         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
   6697         final long id = mInjector.binderClearCallingIdentity();
   6698         try {
   6699             mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
   6700         } finally {
   6701             mInjector.binderRestoreCallingIdentity(id);
   6702         }
   6703     }
   6704 
   6705     @Override
   6706     public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
   6707             PersistableBundle args, boolean parent) {
   6708         if (!mHasFeature) {
   6709             return;
   6710         }
   6711         Preconditions.checkNotNull(admin, "admin is null");
   6712         Preconditions.checkNotNull(agent, "agent is null");
   6713         final int userHandle = UserHandle.getCallingUserId();
   6714         synchronized (this) {
   6715             ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
   6716                     DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
   6717             ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
   6718             saveSettingsLocked(userHandle);
   6719         }
   6720     }
   6721 
   6722     @Override
   6723     public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
   6724             ComponentName agent, int userHandle, boolean parent) {
   6725         if (!mHasFeature) {
   6726             return null;
   6727         }
   6728         Preconditions.checkNotNull(agent, "agent null");
   6729         enforceFullCrossUsersPermission(userHandle);
   6730 
   6731         synchronized (this) {
   6732             final String componentName = agent.flattenToString();
   6733             if (admin != null) {
   6734                 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
   6735                 if (ap == null) return null;
   6736                 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
   6737                 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
   6738                 List<PersistableBundle> result = new ArrayList<>();
   6739                 result.add(trustAgentInfo.options);
   6740                 return result;
   6741             }
   6742 
   6743             // Return strictest policy for this user and profiles that are visible from this user.
   6744             List<PersistableBundle> result = null;
   6745             // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
   6746             // of the options. If any admin doesn't have options, discard options for the rest
   6747             // and return null.
   6748             List<ActiveAdmin> admins =
   6749                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
   6750             boolean allAdminsHaveOptions = true;
   6751             final int N = admins.size();
   6752             for (int i = 0; i < N; i++) {
   6753                 final ActiveAdmin active = admins.get(i);
   6754 
   6755                 final boolean disablesTrust = (active.disabledKeyguardFeatures
   6756                         & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
   6757                 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
   6758                 if (info != null && info.options != null && !info.options.isEmpty()) {
   6759                     if (disablesTrust) {
   6760                         if (result == null) {
   6761                             result = new ArrayList<>();
   6762                         }
   6763                         result.add(info.options);
   6764                     } else {
   6765                         Log.w(LOG_TAG, "Ignoring admin " + active.info
   6766                                 + " because it has trust options but doesn't declare "
   6767                                 + "KEYGUARD_DISABLE_TRUST_AGENTS");
   6768                     }
   6769                 } else if (disablesTrust) {
   6770                     allAdminsHaveOptions = false;
   6771                     break;
   6772                 }
   6773             }
   6774             return allAdminsHaveOptions ? result : null;
   6775         }
   6776     }
   6777 
   6778     @Override
   6779     public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
   6780         Preconditions.checkNotNull(who, "ComponentName is null");
   6781         synchronized (this) {
   6782             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6783 
   6784             int userHandle = UserHandle.getCallingUserId();
   6785             DevicePolicyData userData = getUserData(userHandle);
   6786             userData.mRestrictionsProvider = permissionProvider;
   6787             saveSettingsLocked(userHandle);
   6788         }
   6789     }
   6790 
   6791     @Override
   6792     public ComponentName getRestrictionsProvider(int userHandle) {
   6793         synchronized (this) {
   6794             if (!isCallerWithSystemUid()) {
   6795                 throw new SecurityException("Only the system can query the permission provider");
   6796             }
   6797             DevicePolicyData userData = getUserData(userHandle);
   6798             return userData != null ? userData.mRestrictionsProvider : null;
   6799         }
   6800     }
   6801 
   6802     @Override
   6803     public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
   6804         Preconditions.checkNotNull(who, "ComponentName is null");
   6805         int callingUserId = UserHandle.getCallingUserId();
   6806         synchronized (this) {
   6807             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6808 
   6809             long id = mInjector.binderClearCallingIdentity();
   6810             try {
   6811                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
   6812                 if (parent == null) {
   6813                     Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
   6814                             + "parent");
   6815                     return;
   6816                 }
   6817                 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
   6818                     mIPackageManager.addCrossProfileIntentFilter(
   6819                             filter, who.getPackageName(), callingUserId, parent.id, 0);
   6820                 }
   6821                 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
   6822                     mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
   6823                             parent.id, callingUserId, 0);
   6824                 }
   6825             } catch (RemoteException re) {
   6826                 // Shouldn't happen
   6827             } finally {
   6828                 mInjector.binderRestoreCallingIdentity(id);
   6829             }
   6830         }
   6831     }
   6832 
   6833     @Override
   6834     public void clearCrossProfileIntentFilters(ComponentName who) {
   6835         Preconditions.checkNotNull(who, "ComponentName is null");
   6836         int callingUserId = UserHandle.getCallingUserId();
   6837         synchronized (this) {
   6838             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6839             long id = mInjector.binderClearCallingIdentity();
   6840             try {
   6841                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
   6842                 if (parent == null) {
   6843                     Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
   6844                             + "parent");
   6845                     return;
   6846                 }
   6847                 // Removing those that go from the managed profile to the parent.
   6848                 mIPackageManager.clearCrossProfileIntentFilters(
   6849                         callingUserId, who.getPackageName());
   6850                 // And those that go from the parent to the managed profile.
   6851                 // If we want to support multiple managed profiles, we will have to only remove
   6852                 // those that have callingUserId as their target.
   6853                 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
   6854             } catch (RemoteException re) {
   6855                 // Shouldn't happen
   6856             } finally {
   6857                 mInjector.binderRestoreCallingIdentity(id);
   6858             }
   6859         }
   6860     }
   6861 
   6862     /**
   6863      * @return true if all packages in enabledPackages are either in the list
   6864      * permittedList or are a system app.
   6865      */
   6866     private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
   6867             List<String> permittedList, int userIdToCheck) {
   6868         long id = mInjector.binderClearCallingIdentity();
   6869         try {
   6870             // If we have an enabled packages list for a managed profile the packages
   6871             // we should check are installed for the parent user.
   6872             UserInfo user = getUserInfo(userIdToCheck);
   6873             if (user.isManagedProfile()) {
   6874                 userIdToCheck = user.profileGroupId;
   6875             }
   6876 
   6877             for (String enabledPackage : enabledPackages) {
   6878                 boolean systemService = false;
   6879                 try {
   6880                     ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
   6881                             enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
   6882                     systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
   6883                 } catch (RemoteException e) {
   6884                     Log.i(LOG_TAG, "Can't talk to package managed", e);
   6885                 }
   6886                 if (!systemService && !permittedList.contains(enabledPackage)) {
   6887                     return false;
   6888                 }
   6889             }
   6890         } finally {
   6891             mInjector.binderRestoreCallingIdentity(id);
   6892         }
   6893         return true;
   6894     }
   6895 
   6896     private AccessibilityManager getAccessibilityManagerForUser(int userId) {
   6897         // Not using AccessibilityManager.getInstance because that guesses
   6898         // at the user you require based on callingUid and caches for a given
   6899         // process.
   6900         IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
   6901         IAccessibilityManager service = iBinder == null
   6902                 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
   6903         return new AccessibilityManager(mContext, service, userId);
   6904     }
   6905 
   6906     @Override
   6907     public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
   6908         if (!mHasFeature) {
   6909             return false;
   6910         }
   6911         Preconditions.checkNotNull(who, "ComponentName is null");
   6912 
   6913         if (packageList != null) {
   6914             int userId = UserHandle.getCallingUserId();
   6915             List<AccessibilityServiceInfo> enabledServices = null;
   6916             long id = mInjector.binderClearCallingIdentity();
   6917             try {
   6918                 UserInfo user = getUserInfo(userId);
   6919                 if (user.isManagedProfile()) {
   6920                     userId = user.profileGroupId;
   6921                 }
   6922                 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
   6923                 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
   6924                         AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
   6925             } finally {
   6926                 mInjector.binderRestoreCallingIdentity(id);
   6927             }
   6928 
   6929             if (enabledServices != null) {
   6930                 List<String> enabledPackages = new ArrayList<String>();
   6931                 for (AccessibilityServiceInfo service : enabledServices) {
   6932                     enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
   6933                 }
   6934                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
   6935                         userId)) {
   6936                     Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
   6937                             + "because it contains already enabled accesibility services.");
   6938                     return false;
   6939                 }
   6940             }
   6941         }
   6942 
   6943         synchronized (this) {
   6944             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   6945                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6946             admin.permittedAccessiblityServices = packageList;
   6947             saveSettingsLocked(UserHandle.getCallingUserId());
   6948         }
   6949         return true;
   6950     }
   6951 
   6952     @Override
   6953     public List getPermittedAccessibilityServices(ComponentName who) {
   6954         if (!mHasFeature) {
   6955             return null;
   6956         }
   6957         Preconditions.checkNotNull(who, "ComponentName is null");
   6958 
   6959         synchronized (this) {
   6960             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   6961                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6962             return admin.permittedAccessiblityServices;
   6963         }
   6964     }
   6965 
   6966     @Override
   6967     public List getPermittedAccessibilityServicesForUser(int userId) {
   6968         if (!mHasFeature) {
   6969             return null;
   6970         }
   6971         synchronized (this) {
   6972             List<String> result = null;
   6973             // If we have multiple profiles we return the intersection of the
   6974             // permitted lists. This can happen in cases where we have a device
   6975             // and profile owner.
   6976             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
   6977             for (int profileId : profileIds) {
   6978                 // Just loop though all admins, only device or profiles
   6979                 // owners can have permitted lists set.
   6980                 DevicePolicyData policy = getUserDataUnchecked(profileId);
   6981                 final int N = policy.mAdminList.size();
   6982                 for (int j = 0; j < N; j++) {
   6983                     ActiveAdmin admin = policy.mAdminList.get(j);
   6984                     List<String> fromAdmin = admin.permittedAccessiblityServices;
   6985                     if (fromAdmin != null) {
   6986                         if (result == null) {
   6987                             result = new ArrayList<>(fromAdmin);
   6988                         } else {
   6989                             result.retainAll(fromAdmin);
   6990                         }
   6991                     }
   6992                 }
   6993             }
   6994 
   6995             // If we have a permitted list add all system accessibility services.
   6996             if (result != null) {
   6997                 long id = mInjector.binderClearCallingIdentity();
   6998                 try {
   6999                     UserInfo user = getUserInfo(userId);
   7000                     if (user.isManagedProfile()) {
   7001                         userId = user.profileGroupId;
   7002                     }
   7003                     AccessibilityManager accessibilityManager =
   7004                             getAccessibilityManagerForUser(userId);
   7005                     List<AccessibilityServiceInfo> installedServices =
   7006                             accessibilityManager.getInstalledAccessibilityServiceList();
   7007 
   7008                     if (installedServices != null) {
   7009                         for (AccessibilityServiceInfo service : installedServices) {
   7010                             ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
   7011                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
   7012                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
   7013                                 result.add(serviceInfo.packageName);
   7014                             }
   7015                         }
   7016                     }
   7017                 } finally {
   7018                     mInjector.binderRestoreCallingIdentity(id);
   7019                 }
   7020             }
   7021 
   7022             return result;
   7023         }
   7024     }
   7025 
   7026     @Override
   7027     public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
   7028             int userHandle) {
   7029         if (!mHasFeature) {
   7030             return true;
   7031         }
   7032         Preconditions.checkNotNull(who, "ComponentName is null");
   7033         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
   7034         if (!isCallerWithSystemUid()){
   7035             throw new SecurityException(
   7036                     "Only the system can query if an accessibility service is disabled by admin");
   7037         }
   7038         synchronized (this) {
   7039             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   7040             if (admin == null) {
   7041                 return false;
   7042             }
   7043             if (admin.permittedAccessiblityServices == null) {
   7044                 return true;
   7045             }
   7046             return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
   7047                     admin.permittedAccessiblityServices, userHandle);
   7048         }
   7049     }
   7050 
   7051     private boolean checkCallerIsCurrentUserOrProfile() {
   7052         int callingUserId = UserHandle.getCallingUserId();
   7053         long token = mInjector.binderClearCallingIdentity();
   7054         try {
   7055             UserInfo currentUser;
   7056             UserInfo callingUser = getUserInfo(callingUserId);
   7057             try {
   7058                 currentUser = mInjector.getIActivityManager().getCurrentUser();
   7059             } catch (RemoteException e) {
   7060                 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
   7061                 return false;
   7062             }
   7063 
   7064             if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
   7065                 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
   7066                         + "of a user that isn't the foreground user.");
   7067                 return false;
   7068             }
   7069             if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
   7070                 Slog.e(LOG_TAG, "Cannot set permitted input methods "
   7071                         + "of a user that isn't the foreground user.");
   7072                 return false;
   7073             }
   7074         } finally {
   7075             mInjector.binderRestoreCallingIdentity(token);
   7076         }
   7077         return true;
   7078     }
   7079 
   7080     @Override
   7081     public boolean setPermittedInputMethods(ComponentName who, List packageList) {
   7082         if (!mHasFeature) {
   7083             return false;
   7084         }
   7085         Preconditions.checkNotNull(who, "ComponentName is null");
   7086 
   7087         // TODO When InputMethodManager supports per user calls remove
   7088         //      this restriction.
   7089         if (!checkCallerIsCurrentUserOrProfile()) {
   7090             return false;
   7091         }
   7092 
   7093         if (packageList != null) {
   7094             // InputMethodManager fetches input methods for current user.
   7095             // So this can only be set when calling user is the current user
   7096             // or parent is current user in case of managed profiles.
   7097             InputMethodManager inputMethodManager =
   7098                     mContext.getSystemService(InputMethodManager.class);
   7099             List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
   7100 
   7101             if (enabledImes != null) {
   7102                 List<String> enabledPackages = new ArrayList<String>();
   7103                 for (InputMethodInfo ime : enabledImes) {
   7104                     enabledPackages.add(ime.getPackageName());
   7105                 }
   7106                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
   7107                         mInjector.binderGetCallingUserHandle().getIdentifier())) {
   7108                     Slog.e(LOG_TAG, "Cannot set permitted input methods, "
   7109                             + "because it contains already enabled input method.");
   7110                     return false;
   7111                 }
   7112             }
   7113         }
   7114 
   7115         synchronized (this) {
   7116             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   7117                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7118             admin.permittedInputMethods = packageList;
   7119             saveSettingsLocked(UserHandle.getCallingUserId());
   7120         }
   7121         return true;
   7122     }
   7123 
   7124     @Override
   7125     public List getPermittedInputMethods(ComponentName who) {
   7126         if (!mHasFeature) {
   7127             return null;
   7128         }
   7129         Preconditions.checkNotNull(who, "ComponentName is null");
   7130 
   7131         synchronized (this) {
   7132             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   7133                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7134             return admin.permittedInputMethods;
   7135         }
   7136     }
   7137 
   7138     @Override
   7139     public List getPermittedInputMethodsForCurrentUser() {
   7140         UserInfo currentUser;
   7141         try {
   7142             currentUser = mInjector.getIActivityManager().getCurrentUser();
   7143         } catch (RemoteException e) {
   7144             Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
   7145             // Activity managed is dead, just allow all IMEs
   7146             return null;
   7147         }
   7148 
   7149         int userId = currentUser.id;
   7150         synchronized (this) {
   7151             List<String> result = null;
   7152             // If we have multiple profiles we return the intersection of the
   7153             // permitted lists. This can happen in cases where we have a device
   7154             // and profile owner.
   7155             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
   7156             for (int profileId : profileIds) {
   7157                 // Just loop though all admins, only device or profiles
   7158                 // owners can have permitted lists set.
   7159                 DevicePolicyData policy = getUserDataUnchecked(profileId);
   7160                 final int N = policy.mAdminList.size();
   7161                 for (int j = 0; j < N; j++) {
   7162                     ActiveAdmin admin = policy.mAdminList.get(j);
   7163                     List<String> fromAdmin = admin.permittedInputMethods;
   7164                     if (fromAdmin != null) {
   7165                         if (result == null) {
   7166                             result = new ArrayList<String>(fromAdmin);
   7167                         } else {
   7168                             result.retainAll(fromAdmin);
   7169                         }
   7170                     }
   7171                 }
   7172             }
   7173 
   7174             // If we have a permitted list add all system input methods.
   7175             if (result != null) {
   7176                 InputMethodManager inputMethodManager =
   7177                         mContext.getSystemService(InputMethodManager.class);
   7178                 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
   7179                 long id = mInjector.binderClearCallingIdentity();
   7180                 try {
   7181                     if (imes != null) {
   7182                         for (InputMethodInfo ime : imes) {
   7183                             ServiceInfo serviceInfo = ime.getServiceInfo();
   7184                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
   7185                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
   7186                                 result.add(serviceInfo.packageName);
   7187                             }
   7188                         }
   7189                     }
   7190                 } finally {
   7191                     mInjector.binderRestoreCallingIdentity(id);
   7192                 }
   7193             }
   7194             return result;
   7195         }
   7196     }
   7197 
   7198     @Override
   7199     public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
   7200             int userHandle) {
   7201         if (!mHasFeature) {
   7202             return true;
   7203         }
   7204         Preconditions.checkNotNull(who, "ComponentName is null");
   7205         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
   7206         if (!isCallerWithSystemUid()) {
   7207             throw new SecurityException(
   7208                     "Only the system can query if an input method is disabled by admin");
   7209         }
   7210         synchronized (this) {
   7211             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   7212             if (admin == null) {
   7213                 return false;
   7214             }
   7215             if (admin.permittedInputMethods == null) {
   7216                 return true;
   7217             }
   7218             return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
   7219                     admin.permittedInputMethods, userHandle);
   7220         }
   7221     }
   7222 
   7223     private void sendAdminEnabledBroadcastLocked(int userHandle) {
   7224         DevicePolicyData policyData = getUserData(userHandle);
   7225         if (policyData.mAdminBroadcastPending) {
   7226             // Send the initialization data to profile owner and delete the data
   7227             ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
   7228             if (admin != null) {
   7229                 PersistableBundle initBundle = policyData.mInitBundle;
   7230                 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
   7231                         initBundle == null ? null : new Bundle(initBundle), null);
   7232             }
   7233             policyData.mInitBundle = null;
   7234             policyData.mAdminBroadcastPending = false;
   7235             saveSettingsLocked(userHandle);
   7236         }
   7237     }
   7238 
   7239     @Override
   7240     public UserHandle createAndManageUser(ComponentName admin, String name,
   7241             ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
   7242         Preconditions.checkNotNull(admin, "admin is null");
   7243         Preconditions.checkNotNull(profileOwner, "profileOwner is null");
   7244         if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
   7245             throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
   7246                     + admin + " are not in the same package");
   7247         }
   7248         // Only allow the system user to use this method
   7249         if (!mInjector.binderGetCallingUserHandle().isSystem()) {
   7250             throw new SecurityException("createAndManageUser was called from non-system user");
   7251         }
   7252         if (!mInjector.userManagerIsSplitSystemUser()
   7253                 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
   7254             throw new IllegalArgumentException(
   7255                     "Ephemeral users are only supported on systems with a split system user.");
   7256         }
   7257         // Create user.
   7258         UserHandle user = null;
   7259         synchronized (this) {
   7260             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   7261 
   7262             final long id = mInjector.binderClearCallingIdentity();
   7263             try {
   7264                 int userInfoFlags = 0;
   7265                 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
   7266                     userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
   7267                 }
   7268                 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
   7269                         userInfoFlags);
   7270                 if (userInfo != null) {
   7271                     user = userInfo.getUserHandle();
   7272                 }
   7273             } finally {
   7274                 mInjector.binderRestoreCallingIdentity(id);
   7275             }
   7276         }
   7277         if (user == null) {
   7278             return null;
   7279         }
   7280         // Set admin.
   7281         final long id = mInjector.binderClearCallingIdentity();
   7282         try {
   7283             final String adminPkg = admin.getPackageName();
   7284 
   7285             final int userHandle = user.getIdentifier();
   7286             try {
   7287                 // Install the profile owner if not present.
   7288                 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
   7289                     mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
   7290                 }
   7291             } catch (RemoteException e) {
   7292                 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
   7293                         + "removing created user", e);
   7294                 mUserManager.removeUser(user.getIdentifier());
   7295                 return null;
   7296             }
   7297 
   7298             setActiveAdmin(profileOwner, true, userHandle);
   7299             // User is not started yet, the broadcast by setActiveAdmin will not be received.
   7300             // So we store adminExtras for broadcasting when the user starts for first time.
   7301             synchronized(this) {
   7302                 DevicePolicyData policyData = getUserData(userHandle);
   7303                 policyData.mInitBundle = adminExtras;
   7304                 policyData.mAdminBroadcastPending = true;
   7305                 saveSettingsLocked(userHandle);
   7306             }
   7307             final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
   7308             setProfileOwner(profileOwner, ownerName, userHandle);
   7309 
   7310             if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
   7311                 Settings.Secure.putIntForUser(mContext.getContentResolver(),
   7312                         Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
   7313             }
   7314 
   7315             return user;
   7316         } finally {
   7317             mInjector.binderRestoreCallingIdentity(id);
   7318         }
   7319     }
   7320 
   7321     @Override
   7322     public boolean removeUser(ComponentName who, UserHandle userHandle) {
   7323         Preconditions.checkNotNull(who, "ComponentName is null");
   7324         synchronized (this) {
   7325             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   7326 
   7327             long id = mInjector.binderClearCallingIdentity();
   7328             try {
   7329                 return mUserManager.removeUser(userHandle.getIdentifier());
   7330             } finally {
   7331                 mInjector.binderRestoreCallingIdentity(id);
   7332             }
   7333         }
   7334     }
   7335 
   7336     @Override
   7337     public boolean switchUser(ComponentName who, UserHandle userHandle) {
   7338         Preconditions.checkNotNull(who, "ComponentName is null");
   7339         synchronized (this) {
   7340             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   7341 
   7342             long id = mInjector.binderClearCallingIdentity();
   7343             try {
   7344                 int userId = UserHandle.USER_SYSTEM;
   7345                 if (userHandle != null) {
   7346                     userId = userHandle.getIdentifier();
   7347                 }
   7348                 return mInjector.getIActivityManager().switchUser(userId);
   7349             } catch (RemoteException e) {
   7350                 Log.e(LOG_TAG, "Couldn't switch user", e);
   7351                 return false;
   7352             } finally {
   7353                 mInjector.binderRestoreCallingIdentity(id);
   7354             }
   7355         }
   7356     }
   7357 
   7358     @Override
   7359     public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
   7360         enforceCanManageApplicationRestrictions(who);
   7361 
   7362         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
   7363         final long id = mInjector.binderClearCallingIdentity();
   7364         try {
   7365            Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
   7366            // if no restrictions were saved, mUserManager.getApplicationRestrictions
   7367            // returns null, but DPM method should return an empty Bundle as per JavaDoc
   7368            return bundle != null ? bundle : Bundle.EMPTY;
   7369         } finally {
   7370             mInjector.binderRestoreCallingIdentity(id);
   7371         }
   7372     }
   7373 
   7374     @Override
   7375     public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
   7376             boolean suspended) {
   7377         Preconditions.checkNotNull(who, "ComponentName is null");
   7378         int callingUserId = UserHandle.getCallingUserId();
   7379         synchronized (this) {
   7380             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7381 
   7382             long id = mInjector.binderClearCallingIdentity();
   7383             try {
   7384                 return mIPackageManager.setPackagesSuspendedAsUser(
   7385                         packageNames, suspended, callingUserId);
   7386             } catch (RemoteException re) {
   7387                 // Shouldn't happen.
   7388                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
   7389             } finally {
   7390                 mInjector.binderRestoreCallingIdentity(id);
   7391             }
   7392             return packageNames;
   7393         }
   7394     }
   7395 
   7396     @Override
   7397     public boolean isPackageSuspended(ComponentName who, String packageName) {
   7398         Preconditions.checkNotNull(who, "ComponentName is null");
   7399         int callingUserId = UserHandle.getCallingUserId();
   7400         synchronized (this) {
   7401             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7402 
   7403             long id = mInjector.binderClearCallingIdentity();
   7404             try {
   7405                 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
   7406             } catch (RemoteException re) {
   7407                 // Shouldn't happen.
   7408                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
   7409             } finally {
   7410                 mInjector.binderRestoreCallingIdentity(id);
   7411             }
   7412             return false;
   7413         }
   7414     }
   7415 
   7416     @Override
   7417     public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
   7418         Preconditions.checkNotNull(who, "ComponentName is null");
   7419         if (!UserRestrictionsUtils.isValidRestriction(key)) {
   7420             return;
   7421         }
   7422 
   7423         final int userHandle = mInjector.userHandleGetCallingUserId();
   7424         synchronized (this) {
   7425             ActiveAdmin activeAdmin =
   7426                     getActiveAdminForCallerLocked(who,
   7427                             DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7428             final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
   7429             if (isDeviceOwner) {
   7430                 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
   7431                     throw new SecurityException("Device owner cannot set user restriction " + key);
   7432                 }
   7433             } else { // profile owner
   7434                 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
   7435                     throw new SecurityException("Profile owner cannot set user restriction " + key);
   7436                 }
   7437             }
   7438 
   7439             // Save the restriction to ActiveAdmin.
   7440             activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
   7441             saveSettingsLocked(userHandle);
   7442 
   7443             pushUserRestrictions(userHandle);
   7444 
   7445             sendChangedNotification(userHandle);
   7446         }
   7447     }
   7448 
   7449     private void pushUserRestrictions(int userId) {
   7450         synchronized (this) {
   7451             final Bundle global;
   7452             final Bundle local = new Bundle();
   7453             if (mOwners.isDeviceOwnerUserId(userId)) {
   7454                 global = new Bundle();
   7455 
   7456                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
   7457                 if (deviceOwner == null) {
   7458                     return; // Shouldn't happen.
   7459                 }
   7460 
   7461                 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
   7462                         global, local);
   7463                 // DO can disable camera globally.
   7464                 if (deviceOwner.disableCamera) {
   7465                     global.putBoolean(UserManager.DISALLOW_CAMERA, true);
   7466                 }
   7467             } else {
   7468                 global = null;
   7469 
   7470                 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
   7471                 if (profileOwner != null) {
   7472                     UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
   7473                 }
   7474             }
   7475             // Also merge in *local* camera restriction.
   7476             if (getCameraDisabled(/* who= */ null,
   7477                     userId, /* mergeDeviceOwnerRestriction= */ false)) {
   7478                 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
   7479             }
   7480             mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
   7481         }
   7482     }
   7483 
   7484     @Override
   7485     public Bundle getUserRestrictions(ComponentName who) {
   7486         if (!mHasFeature) {
   7487             return null;
   7488         }
   7489         Preconditions.checkNotNull(who, "ComponentName is null");
   7490         synchronized (this) {
   7491             final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
   7492                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7493             return activeAdmin.userRestrictions;
   7494         }
   7495     }
   7496 
   7497     @Override
   7498     public boolean setApplicationHidden(ComponentName who, String packageName,
   7499             boolean hidden) {
   7500         Preconditions.checkNotNull(who, "ComponentName is null");
   7501         int callingUserId = UserHandle.getCallingUserId();
   7502         synchronized (this) {
   7503             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7504 
   7505             long id = mInjector.binderClearCallingIdentity();
   7506             try {
   7507                 return mIPackageManager.setApplicationHiddenSettingAsUser(
   7508                         packageName, hidden, callingUserId);
   7509             } catch (RemoteException re) {
   7510                 // shouldn't happen
   7511                 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
   7512             } finally {
   7513                 mInjector.binderRestoreCallingIdentity(id);
   7514             }
   7515             return false;
   7516         }
   7517     }
   7518 
   7519     @Override
   7520     public boolean isApplicationHidden(ComponentName who, String packageName) {
   7521         Preconditions.checkNotNull(who, "ComponentName is null");
   7522         int callingUserId = UserHandle.getCallingUserId();
   7523         synchronized (this) {
   7524             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7525 
   7526             long id = mInjector.binderClearCallingIdentity();
   7527             try {
   7528                 return mIPackageManager.getApplicationHiddenSettingAsUser(
   7529                         packageName, callingUserId);
   7530             } catch (RemoteException re) {
   7531                 // shouldn't happen
   7532                 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
   7533             } finally {
   7534                 mInjector.binderRestoreCallingIdentity(id);
   7535             }
   7536             return false;
   7537         }
   7538     }
   7539 
   7540     @Override
   7541     public void enableSystemApp(ComponentName who, String packageName) {
   7542         Preconditions.checkNotNull(who, "ComponentName is null");
   7543         synchronized (this) {
   7544             // This API can only be called by an active device admin,
   7545             // so try to retrieve it to check that the caller is one.
   7546             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7547 
   7548             int userId = UserHandle.getCallingUserId();
   7549             long id = mInjector.binderClearCallingIdentity();
   7550 
   7551             try {
   7552                 if (VERBOSE_LOG) {
   7553                     Slog.v(LOG_TAG, "installing " + packageName + " for "
   7554                             + userId);
   7555                 }
   7556 
   7557                 int parentUserId = getProfileParentId(userId);
   7558                 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
   7559                     throw new IllegalArgumentException("Only system apps can be enabled this way.");
   7560                 }
   7561 
   7562                 // Install the app.
   7563                 mIPackageManager.installExistingPackageAsUser(packageName, userId);
   7564 
   7565             } catch (RemoteException re) {
   7566                 // shouldn't happen
   7567                 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
   7568             } finally {
   7569                 mInjector.binderRestoreCallingIdentity(id);
   7570             }
   7571         }
   7572     }
   7573 
   7574     @Override
   7575     public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
   7576         Preconditions.checkNotNull(who, "ComponentName is null");
   7577         synchronized (this) {
   7578             // This API can only be called by an active device admin,
   7579             // so try to retrieve it to check that the caller is one.
   7580             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7581 
   7582             int userId = UserHandle.getCallingUserId();
   7583             long id = mInjector.binderClearCallingIdentity();
   7584 
   7585             try {
   7586                 int parentUserId = getProfileParentId(userId);
   7587                 List<ResolveInfo> activitiesToEnable = mIPackageManager
   7588                         .queryIntentActivities(intent,
   7589                                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
   7590                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
   7591                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
   7592                                 parentUserId)
   7593                         .getList();
   7594 
   7595                 if (VERBOSE_LOG) {
   7596                     Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
   7597                 }
   7598                 int numberOfAppsInstalled = 0;
   7599                 if (activitiesToEnable != null) {
   7600                     for (ResolveInfo info : activitiesToEnable) {
   7601                         if (info.activityInfo != null) {
   7602                             String packageName = info.activityInfo.packageName;
   7603                             if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
   7604                                 numberOfAppsInstalled++;
   7605                                 mIPackageManager.installExistingPackageAsUser(packageName, userId);
   7606                             } else {
   7607                                 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
   7608                                         + " system app");
   7609                             }
   7610                         }
   7611                     }
   7612                 }
   7613                 return numberOfAppsInstalled;
   7614             } catch (RemoteException e) {
   7615                 // shouldn't happen
   7616                 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
   7617                 return 0;
   7618             } finally {
   7619                 mInjector.binderRestoreCallingIdentity(id);
   7620             }
   7621         }
   7622     }
   7623 
   7624     private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
   7625             throws RemoteException {
   7626         ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
   7627                 userId);
   7628         if (appInfo == null) {
   7629             throw new IllegalArgumentException("The application " + packageName +
   7630                     " is not present on this device");
   7631         }
   7632         return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
   7633     }
   7634 
   7635     @Override
   7636     public void setAccountManagementDisabled(ComponentName who, String accountType,
   7637             boolean disabled) {
   7638         if (!mHasFeature) {
   7639             return;
   7640         }
   7641         Preconditions.checkNotNull(who, "ComponentName is null");
   7642         synchronized (this) {
   7643             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   7644                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7645             if (disabled) {
   7646                 ap.accountTypesWithManagementDisabled.add(accountType);
   7647             } else {
   7648                 ap.accountTypesWithManagementDisabled.remove(accountType);
   7649             }
   7650             saveSettingsLocked(UserHandle.getCallingUserId());
   7651         }
   7652     }
   7653 
   7654     @Override
   7655     public String[] getAccountTypesWithManagementDisabled() {
   7656         return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
   7657     }
   7658 
   7659     @Override
   7660     public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
   7661         enforceFullCrossUsersPermission(userId);
   7662         if (!mHasFeature) {
   7663             return null;
   7664         }
   7665         synchronized (this) {
   7666             DevicePolicyData policy = getUserData(userId);
   7667             final int N = policy.mAdminList.size();
   7668             ArraySet<String> resultSet = new ArraySet<>();
   7669             for (int i = 0; i < N; i++) {
   7670                 ActiveAdmin admin = policy.mAdminList.get(i);
   7671                 resultSet.addAll(admin.accountTypesWithManagementDisabled);
   7672             }
   7673             return resultSet.toArray(new String[resultSet.size()]);
   7674         }
   7675     }
   7676 
   7677     @Override
   7678     public void setUninstallBlocked(ComponentName who, String packageName,
   7679             boolean uninstallBlocked) {
   7680         Preconditions.checkNotNull(who, "ComponentName is null");
   7681         final int userId = UserHandle.getCallingUserId();
   7682         synchronized (this) {
   7683             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7684 
   7685             long id = mInjector.binderClearCallingIdentity();
   7686             try {
   7687                 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
   7688             } catch (RemoteException re) {
   7689                 // Shouldn't happen.
   7690                 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
   7691             } finally {
   7692                 mInjector.binderRestoreCallingIdentity(id);
   7693             }
   7694         }
   7695     }
   7696 
   7697     @Override
   7698     public boolean isUninstallBlocked(ComponentName who, String packageName) {
   7699         // This function should return true if and only if the package is blocked by
   7700         // setUninstallBlocked(). It should still return false for other cases of blocks, such as
   7701         // when the package is a system app, or when it is an active device admin.
   7702         final int userId = UserHandle.getCallingUserId();
   7703 
   7704         synchronized (this) {
   7705             if (who != null) {
   7706                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7707             }
   7708 
   7709             long id = mInjector.binderClearCallingIdentity();
   7710             try {
   7711                 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
   7712             } catch (RemoteException re) {
   7713                 // Shouldn't happen.
   7714                 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
   7715             } finally {
   7716                 mInjector.binderRestoreCallingIdentity(id);
   7717             }
   7718         }
   7719         return false;
   7720     }
   7721 
   7722     @Override
   7723     public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
   7724         if (!mHasFeature) {
   7725             return;
   7726         }
   7727         Preconditions.checkNotNull(who, "ComponentName is null");
   7728         synchronized (this) {
   7729             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   7730                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7731             if (admin.disableCallerId != disabled) {
   7732                 admin.disableCallerId = disabled;
   7733                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   7734             }
   7735         }
   7736     }
   7737 
   7738     @Override
   7739     public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
   7740         if (!mHasFeature) {
   7741             return false;
   7742         }
   7743         Preconditions.checkNotNull(who, "ComponentName is null");
   7744         synchronized (this) {
   7745             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   7746                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7747             return admin.disableCallerId;
   7748         }
   7749     }
   7750 
   7751     @Override
   7752     public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
   7753         enforceCrossUsersPermission(userId);
   7754         synchronized (this) {
   7755             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
   7756             return (admin != null) ? admin.disableCallerId : false;
   7757         }
   7758     }
   7759 
   7760     @Override
   7761     public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
   7762         if (!mHasFeature) {
   7763             return;
   7764         }
   7765         Preconditions.checkNotNull(who, "ComponentName is null");
   7766         synchronized (this) {
   7767             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   7768                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7769             if (admin.disableContactsSearch != disabled) {
   7770                 admin.disableContactsSearch = disabled;
   7771                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
   7772             }
   7773         }
   7774     }
   7775 
   7776     @Override
   7777     public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
   7778         if (!mHasFeature) {
   7779             return false;
   7780         }
   7781         Preconditions.checkNotNull(who, "ComponentName is null");
   7782         synchronized (this) {
   7783             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   7784                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7785             return admin.disableContactsSearch;
   7786         }
   7787     }
   7788 
   7789     @Override
   7790     public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
   7791         enforceCrossUsersPermission(userId);
   7792         synchronized (this) {
   7793             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
   7794             return (admin != null) ? admin.disableContactsSearch : false;
   7795         }
   7796     }
   7797 
   7798     @Override
   7799     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
   7800             boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
   7801         final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
   7802                 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
   7803         final int callingUserId = UserHandle.getCallingUserId();
   7804 
   7805         final long ident = mInjector.binderClearCallingIdentity();
   7806         try {
   7807             synchronized (this) {
   7808                 final int managedUserId = getManagedUserId(callingUserId);
   7809                 if (managedUserId < 0) {
   7810                     return;
   7811                 }
   7812                 if (isCrossProfileQuickContactDisabled(managedUserId)) {
   7813                     if (VERBOSE_LOG) {
   7814                         Log.v(LOG_TAG,
   7815                                 "Cross-profile contacts access disabled for user " + managedUserId);
   7816                     }
   7817                     return;
   7818                 }
   7819                 ContactsInternal.startQuickContactWithErrorToastForUser(
   7820                         mContext, intent, new UserHandle(managedUserId));
   7821             }
   7822         } finally {
   7823             mInjector.binderRestoreCallingIdentity(ident);
   7824         }
   7825     }
   7826 
   7827     /**
   7828      * @return true if cross-profile QuickContact is disabled
   7829      */
   7830     private boolean isCrossProfileQuickContactDisabled(int userId) {
   7831         return getCrossProfileCallerIdDisabledForUser(userId)
   7832                 && getCrossProfileContactsSearchDisabledForUser(userId);
   7833     }
   7834 
   7835     /**
   7836      * @return the user ID of the managed user that is linked to the current user, if any.
   7837      * Otherwise -1.
   7838      */
   7839     public int getManagedUserId(int callingUserId) {
   7840         if (VERBOSE_LOG) {
   7841             Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
   7842         }
   7843 
   7844         for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
   7845             if (ui.id == callingUserId || !ui.isManagedProfile()) {
   7846                 continue; // Caller user self, or not a managed profile.  Skip.
   7847             }
   7848             if (VERBOSE_LOG) {
   7849                 Log.v(LOG_TAG, "Managed user=" + ui.id);
   7850             }
   7851             return ui.id;
   7852         }
   7853         if (VERBOSE_LOG) {
   7854             Log.v(LOG_TAG, "Managed user not found.");
   7855         }
   7856         return -1;
   7857     }
   7858 
   7859     @Override
   7860     public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
   7861         if (!mHasFeature) {
   7862             return;
   7863         }
   7864         Preconditions.checkNotNull(who, "ComponentName is null");
   7865         synchronized (this) {
   7866             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   7867                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7868             if (admin.disableBluetoothContactSharing != disabled) {
   7869                 admin.disableBluetoothContactSharing = disabled;
   7870                 saveSettingsLocked(UserHandle.getCallingUserId());
   7871             }
   7872         }
   7873     }
   7874 
   7875     @Override
   7876     public boolean getBluetoothContactSharingDisabled(ComponentName who) {
   7877         if (!mHasFeature) {
   7878             return false;
   7879         }
   7880         Preconditions.checkNotNull(who, "ComponentName is null");
   7881         synchronized (this) {
   7882             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   7883                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   7884             return admin.disableBluetoothContactSharing;
   7885         }
   7886     }
   7887 
   7888     @Override
   7889     public boolean getBluetoothContactSharingDisabledForUser(int userId) {
   7890         // TODO: Should there be a check to make sure this relationship is
   7891         // within a profile group?
   7892         // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
   7893         synchronized (this) {
   7894             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
   7895             return (admin != null) ? admin.disableBluetoothContactSharing : false;
   7896         }
   7897     }
   7898 
   7899     /**
   7900      * Sets which packages may enter lock task mode.
   7901      *
   7902      * <p>This function can only be called by the device owner or alternatively by the profile owner
   7903      * in case the user is affiliated.
   7904      *
   7905      * @param packages The list of packages allowed to enter lock task mode.
   7906      */
   7907     @Override
   7908     public void setLockTaskPackages(ComponentName who, String[] packages)
   7909             throws SecurityException {
   7910         Preconditions.checkNotNull(who, "ComponentName is null");
   7911         synchronized (this) {
   7912             ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
   7913                 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
   7914             ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
   7915                 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
   7916             if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
   7917                 int userHandle = mInjector.userHandleGetCallingUserId();
   7918                 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
   7919             } else {
   7920                 throw new SecurityException("Admin " + who +
   7921                     " is neither the device owner or affiliated user's profile owner.");
   7922             }
   7923         }
   7924     }
   7925 
   7926     private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
   7927         DevicePolicyData policy = getUserData(userHandle);
   7928         policy.mLockTaskPackages = packages;
   7929 
   7930         // Store the settings persistently.
   7931         saveSettingsLocked(userHandle);
   7932         updateLockTaskPackagesLocked(packages, userHandle);
   7933     }
   7934 
   7935     /**
   7936      * This function returns the list of components allowed to start the task lock mode.
   7937      */
   7938     @Override
   7939     public String[] getLockTaskPackages(ComponentName who) {
   7940         Preconditions.checkNotNull(who, "ComponentName is null");
   7941         synchronized (this) {
   7942             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   7943             int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
   7944             final List<String> packages = getLockTaskPackagesLocked(userHandle);
   7945             return packages.toArray(new String[packages.size()]);
   7946         }
   7947     }
   7948 
   7949     private List<String> getLockTaskPackagesLocked(int userHandle) {
   7950         final DevicePolicyData policy = getUserData(userHandle);
   7951         return policy.mLockTaskPackages;
   7952     }
   7953 
   7954     /**
   7955      * This function lets the caller know whether the given package is allowed to start the
   7956      * lock task mode.
   7957      * @param pkg The package to check
   7958      */
   7959     @Override
   7960     public boolean isLockTaskPermitted(String pkg) {
   7961         // Get current user's devicepolicy
   7962         int uid = mInjector.binderGetCallingUid();
   7963         int userHandle = UserHandle.getUserId(uid);
   7964         DevicePolicyData policy = getUserData(userHandle);
   7965         synchronized (this) {
   7966             for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
   7967                 String lockTaskPackage = policy.mLockTaskPackages.get(i);
   7968 
   7969                 // If the given package equals one of the packages stored our list,
   7970                 // we allow this package to start lock task mode.
   7971                 if (lockTaskPackage.equals(pkg)) {
   7972                     return true;
   7973                 }
   7974             }
   7975         }
   7976         return false;
   7977     }
   7978 
   7979     @Override
   7980     public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
   7981         if (!isCallerWithSystemUid()) {
   7982             throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
   7983         }
   7984         synchronized (this) {
   7985             final DevicePolicyData policy = getUserData(userHandle);
   7986             Bundle adminExtras = new Bundle();
   7987             adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
   7988             for (ActiveAdmin admin : policy.mAdminList) {
   7989                 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
   7990                 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
   7991                 if (ownsDevice || ownsProfile) {
   7992                     if (isEnabled) {
   7993                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
   7994                                 adminExtras, null);
   7995                     } else {
   7996                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
   7997                     }
   7998                 }
   7999             }
   8000         }
   8001     }
   8002 
   8003     @Override
   8004     public void setGlobalSetting(ComponentName who, String setting, String value) {
   8005         Preconditions.checkNotNull(who, "ComponentName is null");
   8006 
   8007         synchronized (this) {
   8008             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   8009 
   8010             // Some settings are no supported any more. However we do not want to throw a
   8011             // SecurityException to avoid breaking apps.
   8012             if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
   8013                 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
   8014                 return;
   8015             }
   8016 
   8017             if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
   8018                 throw new SecurityException(String.format(
   8019                         "Permission denial: device owners cannot update %1$s", setting));
   8020             }
   8021 
   8022             if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
   8023                 // ignore if it contradicts an existing policy
   8024                 long timeMs = getMaximumTimeToLock(
   8025                         who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
   8026                 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
   8027                     return;
   8028                 }
   8029             }
   8030 
   8031             long id = mInjector.binderClearCallingIdentity();
   8032             try {
   8033                 mInjector.settingsGlobalPutString(setting, value);
   8034             } finally {
   8035                 mInjector.binderRestoreCallingIdentity(id);
   8036             }
   8037         }
   8038     }
   8039 
   8040     @Override
   8041     public void setSecureSetting(ComponentName who, String setting, String value) {
   8042         Preconditions.checkNotNull(who, "ComponentName is null");
   8043         int callingUserId = mInjector.userHandleGetCallingUserId();
   8044 
   8045         synchronized (this) {
   8046             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8047 
   8048             if (isDeviceOwner(who, callingUserId)) {
   8049                 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
   8050                     throw new SecurityException(String.format(
   8051                             "Permission denial: Device owners cannot update %1$s", setting));
   8052                 }
   8053             } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
   8054                 throw new SecurityException(String.format(
   8055                         "Permission denial: Profile owners cannot update %1$s", setting));
   8056             }
   8057 
   8058             long id = mInjector.binderClearCallingIdentity();
   8059             try {
   8060                 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
   8061             } finally {
   8062                 mInjector.binderRestoreCallingIdentity(id);
   8063             }
   8064         }
   8065     }
   8066 
   8067     @Override
   8068     public void setMasterVolumeMuted(ComponentName who, boolean on) {
   8069         Preconditions.checkNotNull(who, "ComponentName is null");
   8070         synchronized (this) {
   8071             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8072             setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
   8073         }
   8074     }
   8075 
   8076     @Override
   8077     public boolean isMasterVolumeMuted(ComponentName who) {
   8078         Preconditions.checkNotNull(who, "ComponentName is null");
   8079         synchronized (this) {
   8080             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8081 
   8082             AudioManager audioManager =
   8083                     (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
   8084             return audioManager.isMasterMute();
   8085         }
   8086     }
   8087 
   8088     @Override
   8089     public void setUserIcon(ComponentName who, Bitmap icon) {
   8090         synchronized (this) {
   8091             Preconditions.checkNotNull(who, "ComponentName is null");
   8092             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8093 
   8094             int userId = UserHandle.getCallingUserId();
   8095             long id = mInjector.binderClearCallingIdentity();
   8096             try {
   8097                 mUserManagerInternal.setUserIcon(userId, icon);
   8098             } finally {
   8099                 mInjector.binderRestoreCallingIdentity(id);
   8100             }
   8101         }
   8102     }
   8103 
   8104     @Override
   8105     public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
   8106         Preconditions.checkNotNull(who, "ComponentName is null");
   8107         synchronized (this) {
   8108             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   8109         }
   8110         final int userId = UserHandle.getCallingUserId();
   8111 
   8112         long ident = mInjector.binderClearCallingIdentity();
   8113         try {
   8114             // disallow disabling the keyguard if a password is currently set
   8115             if (disabled && mLockPatternUtils.isSecure(userId)) {
   8116                 return false;
   8117             }
   8118             mLockPatternUtils.setLockScreenDisabled(disabled, userId);
   8119         } finally {
   8120             mInjector.binderRestoreCallingIdentity(ident);
   8121         }
   8122         return true;
   8123     }
   8124 
   8125     @Override
   8126     public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
   8127         int userId = UserHandle.getCallingUserId();
   8128         synchronized (this) {
   8129             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   8130             DevicePolicyData policy = getUserData(userId);
   8131             if (policy.mStatusBarDisabled != disabled) {
   8132                 if (!setStatusBarDisabledInternal(disabled, userId)) {
   8133                     return false;
   8134                 }
   8135                 policy.mStatusBarDisabled = disabled;
   8136                 saveSettingsLocked(userId);
   8137             }
   8138         }
   8139         return true;
   8140     }
   8141 
   8142     private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
   8143         long ident = mInjector.binderClearCallingIdentity();
   8144         try {
   8145             IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
   8146                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
   8147             if (statusBarService != null) {
   8148                 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
   8149                 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
   8150                 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
   8151                 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
   8152                 return true;
   8153             }
   8154         } catch (RemoteException e) {
   8155             Slog.e(LOG_TAG, "Failed to disable the status bar", e);
   8156         } finally {
   8157             mInjector.binderRestoreCallingIdentity(ident);
   8158         }
   8159         return false;
   8160     }
   8161 
   8162     /**
   8163      * We need to update the internal state of whether a user has completed setup once. After
   8164      * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
   8165      * as we don't trust any apps that might try to reset it.
   8166      * <p>
   8167      * Unfortunately, we don't know which user's setup state was changed, so we write all of
   8168      * them.
   8169      */
   8170     void updateUserSetupComplete() {
   8171         List<UserInfo> users = mUserManager.getUsers(true);
   8172         final int N = users.size();
   8173         for (int i = 0; i < N; i++) {
   8174             int userHandle = users.get(i).id;
   8175             if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
   8176                     userHandle) != 0) {
   8177                 DevicePolicyData policy = getUserData(userHandle);
   8178                 if (!policy.mUserSetupComplete) {
   8179                     policy.mUserSetupComplete = true;
   8180                     synchronized (this) {
   8181                         saveSettingsLocked(userHandle);
   8182                     }
   8183                 }
   8184             }
   8185         }
   8186     }
   8187 
   8188     private class SetupContentObserver extends ContentObserver {
   8189 
   8190         private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
   8191                 Settings.Secure.USER_SETUP_COMPLETE);
   8192         private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
   8193                 Settings.Global.DEVICE_PROVISIONED);
   8194 
   8195         public SetupContentObserver(Handler handler) {
   8196             super(handler);
   8197         }
   8198 
   8199         void register() {
   8200             mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
   8201             mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
   8202         }
   8203 
   8204         @Override
   8205         public void onChange(boolean selfChange, Uri uri) {
   8206             if (mUserSetupComplete.equals(uri)) {
   8207                 updateUserSetupComplete();
   8208             } else if (mDeviceProvisioned.equals(uri)) {
   8209                 synchronized (DevicePolicyManagerService.this) {
   8210                     // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
   8211                     // is delayed until device is marked as provisioned.
   8212                     setDeviceOwnerSystemPropertyLocked();
   8213                 }
   8214             }
   8215         }
   8216     }
   8217 
   8218     @VisibleForTesting
   8219     final class LocalService extends DevicePolicyManagerInternal {
   8220         private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
   8221 
   8222         @Override
   8223         public List<String> getCrossProfileWidgetProviders(int profileId) {
   8224             synchronized (DevicePolicyManagerService.this) {
   8225                 if (mOwners == null) {
   8226                     return Collections.emptyList();
   8227                 }
   8228                 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
   8229                 if (ownerComponent == null) {
   8230                     return Collections.emptyList();
   8231                 }
   8232 
   8233                 DevicePolicyData policy = getUserDataUnchecked(profileId);
   8234                 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
   8235 
   8236                 if (admin == null || admin.crossProfileWidgetProviders == null
   8237                         || admin.crossProfileWidgetProviders.isEmpty()) {
   8238                     return Collections.emptyList();
   8239                 }
   8240 
   8241                 return admin.crossProfileWidgetProviders;
   8242             }
   8243         }
   8244 
   8245         @Override
   8246         public void addOnCrossProfileWidgetProvidersChangeListener(
   8247                 OnCrossProfileWidgetProvidersChangeListener listener) {
   8248             synchronized (DevicePolicyManagerService.this) {
   8249                 if (mWidgetProviderListeners == null) {
   8250                     mWidgetProviderListeners = new ArrayList<>();
   8251                 }
   8252                 if (!mWidgetProviderListeners.contains(listener)) {
   8253                     mWidgetProviderListeners.add(listener);
   8254                 }
   8255             }
   8256         }
   8257 
   8258         @Override
   8259         public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
   8260             synchronized(DevicePolicyManagerService.this) {
   8261                 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
   8262             }
   8263         }
   8264 
   8265         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
   8266             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
   8267             synchronized (DevicePolicyManagerService.this) {
   8268                 listeners = new ArrayList<>(mWidgetProviderListeners);
   8269             }
   8270             final int listenerCount = listeners.size();
   8271             for (int i = 0; i < listenerCount; i++) {
   8272                 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
   8273                 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
   8274             }
   8275         }
   8276 
   8277         @Override
   8278         public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
   8279             Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
   8280             intent.putExtra(Intent.EXTRA_USER_ID, userId);
   8281             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   8282 
   8283             // This method is called from AM with its lock held, so don't take the DPMS lock.
   8284             // b/29242568
   8285 
   8286             ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
   8287             if (profileOwner != null) {
   8288                 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
   8289                 return intent;
   8290             }
   8291 
   8292             final Pair<Integer, ComponentName> deviceOwner =
   8293                     mOwners.getDeviceOwnerUserIdAndComponent();
   8294             if (deviceOwner != null && deviceOwner.first == userId) {
   8295                 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
   8296                 return intent;
   8297             }
   8298 
   8299             // We're not specifying the device admin because there isn't one.
   8300             return intent;
   8301         }
   8302     }
   8303 
   8304     /**
   8305      * Returns true if specified admin is allowed to limit passwords and has a
   8306      * {@code passwordQuality} of at least {@code minPasswordQuality}
   8307      */
   8308     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
   8309         if (admin.passwordQuality < minPasswordQuality) {
   8310             return false;
   8311         }
   8312         return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   8313     }
   8314 
   8315     @Override
   8316     public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
   8317         if (policy != null && !policy.isValid()) {
   8318             throw new IllegalArgumentException("Invalid system update policy.");
   8319         }
   8320         synchronized (this) {
   8321             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   8322             if (policy == null) {
   8323                 mOwners.clearSystemUpdatePolicy();
   8324             } else {
   8325                 mOwners.setSystemUpdatePolicy(policy);
   8326             }
   8327             mOwners.writeDeviceOwner();
   8328         }
   8329         mContext.sendBroadcastAsUser(
   8330                 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
   8331                 UserHandle.SYSTEM);
   8332     }
   8333 
   8334     @Override
   8335     public SystemUpdatePolicy getSystemUpdatePolicy() {
   8336         if (UserManager.isDeviceInDemoMode(mContext)) {
   8337             // Pretending to have an automatic update policy when the device is in retail demo
   8338             // mode. This will allow the device to download and install an ota without
   8339             // any user interaction.
   8340             return SystemUpdatePolicy.createAutomaticInstallPolicy();
   8341         }
   8342         synchronized (this) {
   8343             SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
   8344             if (policy != null && !policy.isValid()) {
   8345                 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
   8346                 return null;
   8347             }
   8348             return policy;
   8349         }
   8350     }
   8351 
   8352     /**
   8353      * Checks if the caller of the method is the device owner app.
   8354      *
   8355      * @param callerUid UID of the caller.
   8356      * @return true if the caller is the device owner app
   8357      */
   8358     @VisibleForTesting
   8359     boolean isCallerDeviceOwner(int callerUid) {
   8360         synchronized (this) {
   8361             if (!mOwners.hasDeviceOwner()) {
   8362                 return false;
   8363             }
   8364             if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
   8365                 return false;
   8366             }
   8367             final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
   8368                     .getPackageName();
   8369             final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
   8370 
   8371             for (String pkg : pkgs) {
   8372                 if (deviceOwnerPackageName.equals(pkg)) {
   8373                     return true;
   8374                 }
   8375             }
   8376         }
   8377 
   8378         return false;
   8379     }
   8380 
   8381     @Override
   8382     public void notifyPendingSystemUpdate(long updateReceivedTime) {
   8383         mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
   8384                 "Only the system update service can broadcast update information");
   8385 
   8386         if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
   8387             Slog.w(LOG_TAG, "Only the system update service in the system user " +
   8388                     "can broadcast update information.");
   8389             return;
   8390         }
   8391         Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
   8392         intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
   8393                 updateReceivedTime);
   8394 
   8395         synchronized (this) {
   8396             final String deviceOwnerPackage =
   8397                     mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
   8398                             : null;
   8399             if (deviceOwnerPackage == null) {
   8400                 return;
   8401             }
   8402             final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
   8403 
   8404             ActivityInfo[] receivers = null;
   8405             try {
   8406                 receivers  = mContext.getPackageManager().getPackageInfo(
   8407                         deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
   8408             } catch (NameNotFoundException e) {
   8409                 Log.e(LOG_TAG, "Cannot find device owner package", e);
   8410             }
   8411             if (receivers != null) {
   8412                 long ident = mInjector.binderClearCallingIdentity();
   8413                 try {
   8414                     for (int i = 0; i < receivers.length; i++) {
   8415                         if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
   8416                             intent.setComponent(new ComponentName(deviceOwnerPackage,
   8417                                     receivers[i].name));
   8418                             mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
   8419                         }
   8420                     }
   8421                 } finally {
   8422                     mInjector.binderRestoreCallingIdentity(ident);
   8423                 }
   8424             }
   8425         }
   8426     }
   8427 
   8428     @Override
   8429     public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
   8430         int userId = UserHandle.getCallingUserId();
   8431         synchronized (this) {
   8432             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8433             DevicePolicyData userPolicy = getUserData(userId);
   8434             if (userPolicy.mPermissionPolicy != policy) {
   8435                 userPolicy.mPermissionPolicy = policy;
   8436                 saveSettingsLocked(userId);
   8437             }
   8438         }
   8439     }
   8440 
   8441     @Override
   8442     public int getPermissionPolicy(ComponentName admin) throws RemoteException {
   8443         int userId = UserHandle.getCallingUserId();
   8444         synchronized (this) {
   8445             DevicePolicyData userPolicy = getUserData(userId);
   8446             return userPolicy.mPermissionPolicy;
   8447         }
   8448     }
   8449 
   8450     @Override
   8451     public boolean setPermissionGrantState(ComponentName admin, String packageName,
   8452             String permission, int grantState) throws RemoteException {
   8453         UserHandle user = mInjector.binderGetCallingUserHandle();
   8454         synchronized (this) {
   8455             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8456             long ident = mInjector.binderClearCallingIdentity();
   8457             try {
   8458                 if (getTargetSdk(packageName, user.getIdentifier())
   8459                         < android.os.Build.VERSION_CODES.M) {
   8460                     return false;
   8461                 }
   8462                 final PackageManager packageManager = mContext.getPackageManager();
   8463                 switch (grantState) {
   8464                     case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
   8465                         packageManager.grantRuntimePermission(packageName, permission, user);
   8466                         packageManager.updatePermissionFlags(permission, packageName,
   8467                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
   8468                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
   8469                     } break;
   8470 
   8471                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
   8472                         packageManager.revokeRuntimePermission(packageName,
   8473                                 permission, user);
   8474                         packageManager.updatePermissionFlags(permission, packageName,
   8475                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
   8476                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
   8477                     } break;
   8478 
   8479                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
   8480                         packageManager.updatePermissionFlags(permission, packageName,
   8481                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
   8482                     } break;
   8483                 }
   8484                 return true;
   8485             } catch (SecurityException se) {
   8486                 return false;
   8487             } finally {
   8488                 mInjector.binderRestoreCallingIdentity(ident);
   8489             }
   8490         }
   8491     }
   8492 
   8493     @Override
   8494     public int getPermissionGrantState(ComponentName admin, String packageName,
   8495             String permission) throws RemoteException {
   8496         PackageManager packageManager = mContext.getPackageManager();
   8497 
   8498         UserHandle user = mInjector.binderGetCallingUserHandle();
   8499         synchronized (this) {
   8500             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8501             long ident = mInjector.binderClearCallingIdentity();
   8502             try {
   8503                 int granted = mIPackageManager.checkPermission(permission,
   8504                         packageName, user.getIdentifier());
   8505                 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
   8506                 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
   8507                         != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
   8508                     // Not controlled by policy
   8509                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
   8510                 } else {
   8511                     // Policy controlled so return result based on permission grant state
   8512                     return granted == PackageManager.PERMISSION_GRANTED
   8513                             ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
   8514                             : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
   8515                 }
   8516             } finally {
   8517                 mInjector.binderRestoreCallingIdentity(ident);
   8518             }
   8519         }
   8520     }
   8521 
   8522     boolean isPackageInstalledForUser(String packageName, int userHandle) {
   8523         try {
   8524             PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
   8525                     userHandle);
   8526             return (pi != null) && (pi.applicationInfo.flags != 0);
   8527         } catch (RemoteException re) {
   8528             throw new RuntimeException("Package manager has died", re);
   8529         }
   8530     }
   8531 
   8532     @Override
   8533     public boolean isProvisioningAllowed(String action) {
   8534         if (!mHasFeature) {
   8535             return false;
   8536         }
   8537 
   8538         final int callingUserId = mInjector.userHandleGetCallingUserId();
   8539         if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
   8540             if (!hasFeatureManagedUsers()) {
   8541                 return false;
   8542             }
   8543             synchronized (this) {
   8544                 if (mOwners.hasDeviceOwner()) {
   8545                     if (!mInjector.userManagerIsSplitSystemUser()) {
   8546                         // Only split-system-user systems support managed-profiles in combination with
   8547                         // device-owner.
   8548                         return false;
   8549                     }
   8550                     if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
   8551                         // Only system device-owner supports managed-profiles. Non-system device-owner
   8552                         // doesn't.
   8553                         return false;
   8554                     }
   8555                     if (callingUserId == UserHandle.USER_SYSTEM) {
   8556                         // Managed-profiles cannot be setup on the system user, only regular users.
   8557                         return false;
   8558                     }
   8559                 }
   8560             }
   8561             if (getProfileOwner(callingUserId) != null) {
   8562                 // Managed user cannot have a managed profile.
   8563                 return false;
   8564             }
   8565             final long ident = mInjector.binderClearCallingIdentity();
   8566             try {
   8567                 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
   8568                     return false;
   8569                 }
   8570             } finally {
   8571                 mInjector.binderRestoreCallingIdentity(ident);
   8572             }
   8573             return true;
   8574         } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
   8575             return isDeviceOwnerProvisioningAllowed(callingUserId);
   8576         } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
   8577             if (!hasFeatureManagedUsers()) {
   8578                 return false;
   8579             }
   8580             if (!mInjector.userManagerIsSplitSystemUser()) {
   8581                 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
   8582                 return false;
   8583             }
   8584             if (callingUserId == UserHandle.USER_SYSTEM) {
   8585                 // System user cannot be a managed user.
   8586                 return false;
   8587             }
   8588             if (hasUserSetupCompleted(callingUserId)) {
   8589                 return false;
   8590             }
   8591             return true;
   8592         } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
   8593             if (!mInjector.userManagerIsSplitSystemUser()) {
   8594                 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
   8595                 return false;
   8596             }
   8597             return isDeviceOwnerProvisioningAllowed(callingUserId);
   8598         }
   8599         throw new IllegalArgumentException("Unknown provisioning action " + action);
   8600     }
   8601 
   8602     /*
   8603      * The device owner can only be set before the setup phase of the primary user has completed,
   8604      * except for adb command if no accounts or additional users are present on the device.
   8605      */
   8606     private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreConditionLocked(
   8607             @Nullable ComponentName owner, int deviceOwnerUserId, boolean isAdb) {
   8608         if (mOwners.hasDeviceOwner()) {
   8609             return CODE_HAS_DEVICE_OWNER;
   8610         }
   8611         if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
   8612             return CODE_USER_HAS_PROFILE_OWNER;
   8613         }
   8614         if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
   8615             return CODE_USER_NOT_RUNNING;
   8616         }
   8617         if (isAdb) {
   8618             // if shell command runs after user setup completed check device status. Otherwise, OK.
   8619             if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
   8620                 if (!mInjector.userManagerIsSplitSystemUser()) {
   8621                     if (mUserManager.getUserCount() > 1) {
   8622                         return CODE_NONSYSTEM_USER_EXISTS;
   8623                     }
   8624                     if (hasIncompatibleAccountsLocked(UserHandle.USER_SYSTEM, owner)) {
   8625                         return CODE_ACCOUNTS_NOT_EMPTY;
   8626                     }
   8627                 } else {
   8628                     // STOPSHIP Do proper check in split user mode
   8629                 }
   8630             }
   8631             return CODE_OK;
   8632         } else {
   8633             if (!mInjector.userManagerIsSplitSystemUser()) {
   8634                 // In non-split user mode, DO has to be user 0
   8635                 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
   8636                     return CODE_NOT_SYSTEM_USER;
   8637                 }
   8638                 // In non-split user mode, only provision DO before setup wizard completes
   8639                 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
   8640                     return CODE_USER_SETUP_COMPLETED;
   8641                 }
   8642             } else {
   8643                 // STOPSHIP Do proper check in split user mode
   8644             }
   8645             return CODE_OK;
   8646         }
   8647     }
   8648 
   8649     private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
   8650         synchronized (this) {
   8651             return CODE_OK == checkSetDeviceOwnerPreConditionLocked(
   8652                     /* owner unknown */ null, deviceOwnerUserId, /* isAdb */ false);
   8653         }
   8654     }
   8655 
   8656     private boolean hasFeatureManagedUsers() {
   8657         try {
   8658             return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
   8659         } catch (RemoteException e) {
   8660             return false;
   8661         }
   8662     }
   8663 
   8664     @Override
   8665     public String getWifiMacAddress(ComponentName admin) {
   8666         // Make sure caller has DO.
   8667         synchronized (this) {
   8668             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   8669         }
   8670 
   8671         final long ident = mInjector.binderClearCallingIdentity();
   8672         try {
   8673             final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
   8674             if (wifiInfo == null) {
   8675                 return null;
   8676             }
   8677             return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
   8678         } finally {
   8679             mInjector.binderRestoreCallingIdentity(ident);
   8680         }
   8681     }
   8682 
   8683     /**
   8684      * Returns the target sdk version number that the given packageName was built for
   8685      * in the given user.
   8686      */
   8687     private int getTargetSdk(String packageName, int userId) {
   8688         final ApplicationInfo ai;
   8689         try {
   8690             ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
   8691             final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
   8692             return targetSdkVersion;
   8693         } catch (RemoteException e) {
   8694             // Shouldn't happen
   8695             return 0;
   8696         }
   8697     }
   8698 
   8699     @Override
   8700     public boolean isManagedProfile(ComponentName admin) {
   8701         synchronized (this) {
   8702             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8703         }
   8704         final int callingUserId = mInjector.userHandleGetCallingUserId();
   8705         final UserInfo user = getUserInfo(callingUserId);
   8706         return user != null && user.isManagedProfile();
   8707     }
   8708 
   8709     @Override
   8710     public boolean isSystemOnlyUser(ComponentName admin) {
   8711         synchronized (this) {
   8712             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   8713         }
   8714         final int callingUserId = mInjector.userHandleGetCallingUserId();
   8715         return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
   8716     }
   8717 
   8718     @Override
   8719     public void reboot(ComponentName admin) {
   8720         Preconditions.checkNotNull(admin);
   8721         // Make sure caller has DO.
   8722         synchronized (this) {
   8723             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   8724         }
   8725         long ident = mInjector.binderClearCallingIdentity();
   8726         try {
   8727             // Make sure there are no ongoing calls on the device.
   8728             if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
   8729                 throw new IllegalStateException("Cannot be called with ongoing call on the device");
   8730             }
   8731             mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
   8732         } finally {
   8733             mInjector.binderRestoreCallingIdentity(ident);
   8734         }
   8735     }
   8736 
   8737     @Override
   8738     public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
   8739         if (!mHasFeature) {
   8740             return;
   8741         }
   8742         Preconditions.checkNotNull(who, "ComponentName is null");
   8743         final int userHandle = mInjector.userHandleGetCallingUserId();
   8744         synchronized (this) {
   8745             ActiveAdmin admin = getActiveAdminForUidLocked(who,
   8746                     mInjector.binderGetCallingUid());
   8747             if (!TextUtils.equals(admin.shortSupportMessage, message)) {
   8748                 admin.shortSupportMessage = message;
   8749                 saveSettingsLocked(userHandle);
   8750             }
   8751         }
   8752     }
   8753 
   8754     @Override
   8755     public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
   8756         if (!mHasFeature) {
   8757             return null;
   8758         }
   8759         Preconditions.checkNotNull(who, "ComponentName is null");
   8760         synchronized (this) {
   8761             ActiveAdmin admin = getActiveAdminForUidLocked(who,
   8762                     mInjector.binderGetCallingUid());
   8763             return admin.shortSupportMessage;
   8764         }
   8765     }
   8766 
   8767     @Override
   8768     public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
   8769         if (!mHasFeature) {
   8770             return;
   8771         }
   8772         Preconditions.checkNotNull(who, "ComponentName is null");
   8773         final int userHandle = mInjector.userHandleGetCallingUserId();
   8774         synchronized (this) {
   8775             ActiveAdmin admin = getActiveAdminForUidLocked(who,
   8776                     mInjector.binderGetCallingUid());
   8777             if (!TextUtils.equals(admin.longSupportMessage, message)) {
   8778                 admin.longSupportMessage = message;
   8779                 saveSettingsLocked(userHandle);
   8780             }
   8781         }
   8782     }
   8783 
   8784     @Override
   8785     public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
   8786         if (!mHasFeature) {
   8787             return null;
   8788         }
   8789         Preconditions.checkNotNull(who, "ComponentName is null");
   8790         synchronized (this) {
   8791             ActiveAdmin admin = getActiveAdminForUidLocked(who,
   8792                     mInjector.binderGetCallingUid());
   8793             return admin.longSupportMessage;
   8794         }
   8795     }
   8796 
   8797     @Override
   8798     public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
   8799         if (!mHasFeature) {
   8800             return null;
   8801         }
   8802         Preconditions.checkNotNull(who, "ComponentName is null");
   8803         if (!isCallerWithSystemUid()) {
   8804             throw new SecurityException("Only the system can query support message for user");
   8805         }
   8806         synchronized (this) {
   8807             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   8808             if (admin != null) {
   8809                 return admin.shortSupportMessage;
   8810             }
   8811         }
   8812         return null;
   8813     }
   8814 
   8815     @Override
   8816     public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
   8817         if (!mHasFeature) {
   8818             return null;
   8819         }
   8820         Preconditions.checkNotNull(who, "ComponentName is null");
   8821         if (!isCallerWithSystemUid()) {
   8822             throw new SecurityException("Only the system can query support message for user");
   8823         }
   8824         synchronized (this) {
   8825             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   8826             if (admin != null) {
   8827                 return admin.longSupportMessage;
   8828             }
   8829         }
   8830         return null;
   8831     }
   8832 
   8833     @Override
   8834     public void setOrganizationColor(@NonNull ComponentName who, int color) {
   8835         if (!mHasFeature) {
   8836             return;
   8837         }
   8838         Preconditions.checkNotNull(who, "ComponentName is null");
   8839         final int userHandle = mInjector.userHandleGetCallingUserId();
   8840         enforceManagedProfile(userHandle, "set organization color");
   8841         synchronized (this) {
   8842             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   8843                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8844             admin.organizationColor = color;
   8845             saveSettingsLocked(userHandle);
   8846         }
   8847     }
   8848 
   8849     @Override
   8850     public void setOrganizationColorForUser(int color, int userId) {
   8851         if (!mHasFeature) {
   8852             return;
   8853         }
   8854         enforceFullCrossUsersPermission(userId);
   8855         enforceManageUsers();
   8856         enforceManagedProfile(userId, "set organization color");
   8857         synchronized (this) {
   8858             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
   8859             admin.organizationColor = color;
   8860             saveSettingsLocked(userId);
   8861         }
   8862     }
   8863 
   8864     @Override
   8865     public int getOrganizationColor(@NonNull ComponentName who) {
   8866         if (!mHasFeature) {
   8867             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
   8868         }
   8869         Preconditions.checkNotNull(who, "ComponentName is null");
   8870         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
   8871         synchronized (this) {
   8872             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   8873                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8874             return admin.organizationColor;
   8875         }
   8876     }
   8877 
   8878     @Override
   8879     public int getOrganizationColorForUser(int userHandle) {
   8880         if (!mHasFeature) {
   8881             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
   8882         }
   8883         enforceFullCrossUsersPermission(userHandle);
   8884         enforceManagedProfile(userHandle, "get organization color");
   8885         synchronized (this) {
   8886             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
   8887             return (profileOwner != null)
   8888                     ? profileOwner.organizationColor
   8889                     : ActiveAdmin.DEF_ORGANIZATION_COLOR;
   8890         }
   8891     }
   8892 
   8893     @Override
   8894     public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
   8895         if (!mHasFeature) {
   8896             return;
   8897         }
   8898         Preconditions.checkNotNull(who, "ComponentName is null");
   8899         final int userHandle = mInjector.userHandleGetCallingUserId();
   8900         enforceManagedProfile(userHandle, "set organization name");
   8901         synchronized (this) {
   8902             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   8903                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8904             if (!TextUtils.equals(admin.organizationName, text)) {
   8905                 admin.organizationName = (text == null || text.length() == 0)
   8906                         ? null : text.toString();
   8907                 saveSettingsLocked(userHandle);
   8908             }
   8909         }
   8910     }
   8911 
   8912     @Override
   8913     public CharSequence getOrganizationName(@NonNull ComponentName who) {
   8914         if (!mHasFeature) {
   8915             return null;
   8916         }
   8917         Preconditions.checkNotNull(who, "ComponentName is null");
   8918         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
   8919         synchronized(this) {
   8920             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   8921                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8922             return admin.organizationName;
   8923         }
   8924     }
   8925 
   8926     @Override
   8927     public CharSequence getOrganizationNameForUser(int userHandle) {
   8928         if (!mHasFeature) {
   8929             return null;
   8930         }
   8931         enforceFullCrossUsersPermission(userHandle);
   8932         enforceManagedProfile(userHandle, "get organization name");
   8933         synchronized (this) {
   8934             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
   8935             return (profileOwner != null)
   8936                     ? profileOwner.organizationName
   8937                     : null;
   8938         }
   8939     }
   8940 
   8941     @Override
   8942     public void setAffiliationIds(ComponentName admin, List<String> ids) {
   8943         final Set<String> affiliationIds = new ArraySet<String>(ids);
   8944         final int callingUserId = mInjector.userHandleGetCallingUserId();
   8945 
   8946         synchronized (this) {
   8947             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   8948             getUserData(callingUserId).mAffiliationIds = affiliationIds;
   8949             saveSettingsLocked(callingUserId);
   8950             if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
   8951                 // Affiliation ids specified by the device owner are additionally stored in
   8952                 // UserHandle.USER_SYSTEM's DevicePolicyData.
   8953                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
   8954                 saveSettingsLocked(UserHandle.USER_SYSTEM);
   8955             }
   8956         }
   8957     }
   8958 
   8959     @Override
   8960     public boolean isAffiliatedUser() {
   8961         final int callingUserId = mInjector.userHandleGetCallingUserId();
   8962 
   8963         synchronized (this) {
   8964             if (mOwners.getDeviceOwnerUserId() == callingUserId) {
   8965                 // The user that the DO is installed on is always affiliated.
   8966                 return true;
   8967             }
   8968             final ComponentName profileOwner = getProfileOwner(callingUserId);
   8969             if (profileOwner == null
   8970                     || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
   8971                 return false;
   8972             }
   8973             final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
   8974             final Set<String> deviceAffiliationIds =
   8975                     getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
   8976             for (String id : userAffiliationIds) {
   8977                 if (deviceAffiliationIds.contains(id)) {
   8978                     return true;
   8979                 }
   8980             }
   8981         }
   8982         return false;
   8983     }
   8984 
   8985     private synchronized void disableDeviceOwnerManagedSingleUserFeaturesIfNeeded() {
   8986         if (!isDeviceOwnerManagedSingleUserDevice()) {
   8987             mInjector.securityLogSetLoggingEnabledProperty(false);
   8988             Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user device.");
   8989             if (mOwners.hasDeviceOwner()) {
   8990                 setBackupServiceEnabledInternal(false);
   8991                 Slog.w(LOG_TAG, "Backup is off as it's a managed device that has more that one user.");
   8992             }
   8993         }
   8994     }
   8995 
   8996     @Override
   8997     public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
   8998         Preconditions.checkNotNull(admin);
   8999         ensureDeviceOwnerManagingSingleUser(admin);
   9000 
   9001         synchronized (this) {
   9002             if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
   9003                 return;
   9004             }
   9005             mInjector.securityLogSetLoggingEnabledProperty(enabled);
   9006             if (enabled) {
   9007                 mSecurityLogMonitor.start();
   9008             } else {
   9009                 mSecurityLogMonitor.stop();
   9010             }
   9011         }
   9012     }
   9013 
   9014     @Override
   9015     public boolean isSecurityLoggingEnabled(ComponentName admin) {
   9016         Preconditions.checkNotNull(admin);
   9017         synchronized (this) {
   9018             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   9019             return mInjector.securityLogGetLoggingEnabledProperty();
   9020         }
   9021     }
   9022 
   9023     @Override
   9024     public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
   9025         Preconditions.checkNotNull(admin);
   9026         ensureDeviceOwnerManagingSingleUser(admin);
   9027 
   9028         if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
   9029             return null;
   9030         }
   9031 
   9032         ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
   9033         try {
   9034             SecurityLog.readPreviousEvents(output);
   9035             return new ParceledListSlice<SecurityEvent>(output);
   9036         } catch (IOException e) {
   9037             Slog.w(LOG_TAG, "Fail to read previous events" , e);
   9038             return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
   9039         }
   9040     }
   9041 
   9042     @Override
   9043     public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
   9044         Preconditions.checkNotNull(admin);
   9045         ensureDeviceOwnerManagingSingleUser(admin);
   9046 
   9047         List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
   9048         return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
   9049     }
   9050 
   9051     private void enforceCanManageDeviceAdmin() {
   9052         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
   9053                 null);
   9054     }
   9055 
   9056     private void enforceCanManageProfileAndDeviceOwners() {
   9057         mContext.enforceCallingOrSelfPermission(
   9058                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
   9059     }
   9060 
   9061     @Override
   9062     public boolean isUninstallInQueue(final String packageName) {
   9063         enforceCanManageDeviceAdmin();
   9064         final int userId = mInjector.userHandleGetCallingUserId();
   9065         Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
   9066         synchronized (this) {
   9067             return mPackagesToRemove.contains(packageUserPair);
   9068         }
   9069     }
   9070 
   9071     @Override
   9072     public void uninstallPackageWithActiveAdmins(final String packageName) {
   9073         enforceCanManageDeviceAdmin();
   9074         Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
   9075 
   9076         final int userId = mInjector.userHandleGetCallingUserId();
   9077 
   9078         enforceUserUnlocked(userId);
   9079 
   9080         final ComponentName profileOwner = getProfileOwner(userId);
   9081         if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
   9082             throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
   9083         }
   9084 
   9085         final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
   9086         if (getDeviceOwnerUserId() == userId && deviceOwner != null
   9087                 && packageName.equals(deviceOwner.getPackageName())) {
   9088             throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
   9089         }
   9090 
   9091         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
   9092         synchronized (this) {
   9093             mPackagesToRemove.add(packageUserPair);
   9094         }
   9095 
   9096         // All active admins on the user.
   9097         final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
   9098 
   9099         // Active admins in the target package.
   9100         final List<ComponentName> packageActiveAdmins = new ArrayList<>();
   9101         if (allActiveAdmins != null) {
   9102             for (ComponentName activeAdmin : allActiveAdmins) {
   9103                 if (packageName.equals(activeAdmin.getPackageName())) {
   9104                     packageActiveAdmins.add(activeAdmin);
   9105                     removeActiveAdmin(activeAdmin, userId);
   9106                 }
   9107             }
   9108         }
   9109         if (packageActiveAdmins.size() == 0) {
   9110             startUninstallIntent(packageName, userId);
   9111         } else {
   9112             mHandler.postDelayed(new Runnable() {
   9113                 @Override
   9114                 public void run() {
   9115                     for (ComponentName activeAdmin : packageActiveAdmins) {
   9116                         removeAdminArtifacts(activeAdmin, userId);
   9117                     }
   9118                     startUninstallIntent(packageName, userId);
   9119                 }
   9120             }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
   9121         }
   9122     }
   9123 
   9124     @Override
   9125     public boolean isDeviceProvisioned() {
   9126         return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
   9127     }
   9128 
   9129     private void removePackageIfRequired(final String packageName, final int userId) {
   9130         if (!packageHasActiveAdmins(packageName, userId)) {
   9131             // Will not do anything if uninstall was not requested or was already started.
   9132             startUninstallIntent(packageName, userId);
   9133         }
   9134     }
   9135 
   9136     private void startUninstallIntent(final String packageName, final int userId) {
   9137         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
   9138         synchronized (this) {
   9139             if (!mPackagesToRemove.contains(packageUserPair)) {
   9140                 // Do nothing if uninstall was not requested or was already started.
   9141                 return;
   9142             }
   9143             mPackagesToRemove.remove(packageUserPair);
   9144         }
   9145         try {
   9146             if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
   9147                 // Package does not exist. Nothing to do.
   9148                 return;
   9149             }
   9150         } catch (RemoteException re) {
   9151             Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
   9152         }
   9153 
   9154         try { // force stop the package before uninstalling
   9155             mInjector.getIActivityManager().forceStopPackage(packageName, userId);
   9156         } catch (RemoteException re) {
   9157             Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
   9158         }
   9159         final Uri packageURI = Uri.parse("package:" + packageName);
   9160         final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
   9161         uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   9162         mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
   9163     }
   9164 
   9165     /**
   9166      * Removes the admin from the policy. Ideally called after the admin's
   9167      * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
   9168      *
   9169      * @param adminReceiver The admin to remove
   9170      * @param userHandle The user for which this admin has to be removed.
   9171      */
   9172     private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
   9173         synchronized (this) {
   9174             final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
   9175             if (admin == null) {
   9176                 return;
   9177             }
   9178             final DevicePolicyData policy = getUserData(userHandle);
   9179             final boolean doProxyCleanup = admin.info.usesPolicy(
   9180                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
   9181             policy.mAdminList.remove(admin);
   9182             policy.mAdminMap.remove(adminReceiver);
   9183             validatePasswordOwnerLocked(policy);
   9184             if (doProxyCleanup) {
   9185                 resetGlobalProxyLocked(policy);
   9186             }
   9187             saveSettingsLocked(userHandle);
   9188             updateMaximumTimeToLockLocked(userHandle);
   9189             policy.mRemovingAdmins.remove(adminReceiver);
   9190 
   9191             Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
   9192         }
   9193         // The removed admin might have disabled camera, so update user
   9194         // restrictions.
   9195         pushUserRestrictions(userHandle);
   9196     }
   9197 
   9198     @Override
   9199     public void setDeviceProvisioningConfigApplied() {
   9200         enforceManageUsers();
   9201         synchronized (this) {
   9202             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
   9203             policy.mDeviceProvisioningConfigApplied = true;
   9204             saveSettingsLocked(UserHandle.USER_SYSTEM);
   9205         }
   9206     }
   9207 
   9208     @Override
   9209     public boolean isDeviceProvisioningConfigApplied() {
   9210         enforceManageUsers();
   9211         synchronized (this) {
   9212             final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
   9213             return policy.mDeviceProvisioningConfigApplied;
   9214         }
   9215     }
   9216 
   9217     /**
   9218      * Return true if a given user has any accounts that'll prevent installing a device or profile
   9219      * owner {@code owner}.
   9220      * - If the user has no accounts, then return false.
   9221      * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
   9222      * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
   9223      *   ..._DISALLOWED, return true.
   9224      * - Otherwise return false.
   9225      */
   9226     private boolean hasIncompatibleAccountsLocked(int userId, @Nullable ComponentName owner) {
   9227         final long token = mInjector.binderClearCallingIdentity();
   9228         try {
   9229             final AccountManager am = AccountManager.get(mContext);
   9230             final Account accounts[] = am.getAccountsAsUser(userId);
   9231             if (accounts.length == 0) {
   9232                 return false;
   9233             }
   9234             final String[] feature_allow =
   9235                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
   9236             final String[] feature_disallow =
   9237                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
   9238 
   9239             // Even if we find incompatible accounts along the way, we still check all accounts
   9240             // for logging.
   9241             boolean compatible = true;
   9242             for (Account account : accounts) {
   9243                 if (hasAccountFeatures(am, account, feature_disallow)) {
   9244                     Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
   9245                     compatible = false;
   9246                 }
   9247                 if (!hasAccountFeatures(am, account, feature_allow)) {
   9248                     Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
   9249                     compatible = false;
   9250                 }
   9251             }
   9252             if (compatible) {
   9253                 Log.w(LOG_TAG, "All accounts are compatible");
   9254             } else {
   9255                 Log.e(LOG_TAG, "Found incompatible accounts");
   9256             }
   9257 
   9258             // Then check if the owner is test-only.
   9259             String log;
   9260             if (owner == null) {
   9261                 // Owner is unknown.  Suppose it's not test-only
   9262                 compatible = false;
   9263                 log = "Only test-only device/profile owner can be installed with accounts";
   9264             } else if (isAdminTestOnlyLocked(owner, userId)) {
   9265                 if (compatible) {
   9266                     log = "Installing test-only owner " + owner;
   9267                 } else {
   9268                     log = "Can't install test-only owner " + owner + " with incompatible accounts";
   9269                 }
   9270             } else {
   9271                 compatible = false;
   9272                 log = "Can't install non test-only owner " + owner + " with accounts";
   9273             }
   9274             if (compatible) {
   9275                 Log.w(LOG_TAG, log);
   9276             } else {
   9277                 Log.e(LOG_TAG, log);
   9278             }
   9279             return !compatible;
   9280         } finally {
   9281             mInjector.binderRestoreCallingIdentity(token);
   9282         }
   9283     }
   9284 
   9285     private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
   9286         try {
   9287             return am.hasFeatures(account, features, null, null).getResult();
   9288         } catch (Exception e) {
   9289             Log.w(LOG_TAG, "Failed to get account feature", e);
   9290             return false;
   9291         }
   9292     }
   9293 
   9294     @Override
   9295     public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
   9296         Preconditions.checkNotNull(admin);
   9297         if (!mHasFeature) {
   9298             return;
   9299         }
   9300         ensureDeviceOwnerManagingSingleUser(admin);
   9301         setBackupServiceEnabledInternal(enabled);
   9302     }
   9303 
   9304     private synchronized void setBackupServiceEnabledInternal(boolean enabled) {
   9305         long ident = mInjector.binderClearCallingIdentity();
   9306         try {
   9307             IBackupManager ibm = mInjector.getIBackupManager();
   9308             if (ibm != null) {
   9309                 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
   9310             }
   9311         } catch (RemoteException e) {
   9312             throw new IllegalStateException(
   9313                 "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
   9314         } finally {
   9315             mInjector.binderRestoreCallingIdentity(ident);
   9316         }
   9317     }
   9318 
   9319     @Override
   9320     public boolean isBackupServiceEnabled(ComponentName admin) {
   9321         Preconditions.checkNotNull(admin);
   9322         if (!mHasFeature) {
   9323             return true;
   9324         }
   9325         synchronized (this) {
   9326             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   9327             try {
   9328                 IBackupManager ibm = mInjector.getIBackupManager();
   9329                 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
   9330             } catch (RemoteException e) {
   9331                 throw new IllegalStateException("Failed requesting backup service state.", e);
   9332             }
   9333         }
   9334     }
   9335 }
   9336