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 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
     25 import static org.xmlpull.v1.XmlPullParser.END_TAG;
     26 import static org.xmlpull.v1.XmlPullParser.TEXT;
     27 
     28 import android.Manifest.permission;
     29 import android.accessibilityservice.AccessibilityServiceInfo;
     30 import android.accounts.AccountManager;
     31 import android.app.Activity;
     32 import android.app.ActivityManagerNative;
     33 import android.app.AlarmManager;
     34 import android.app.AppGlobals;
     35 import android.app.IActivityManager;
     36 import android.app.Notification;
     37 import android.app.NotificationManager;
     38 import android.app.PendingIntent;
     39 import android.app.StatusBarManager;
     40 import android.app.admin.DeviceAdminInfo;
     41 import android.app.admin.DeviceAdminReceiver;
     42 import android.app.admin.DevicePolicyManager;
     43 import android.app.admin.DevicePolicyManagerInternal;
     44 import android.app.admin.IDevicePolicyManager;
     45 import android.app.admin.SystemUpdatePolicy;
     46 import android.app.backup.IBackupManager;
     47 import android.content.BroadcastReceiver;
     48 import android.content.ComponentName;
     49 import android.content.ContentResolver;
     50 import android.content.Context;
     51 import android.content.Intent;
     52 import android.content.IntentFilter;
     53 import android.content.pm.ActivityInfo;
     54 import android.content.pm.ApplicationInfo;
     55 import android.content.pm.IPackageManager;
     56 import android.content.pm.PackageManager;
     57 import android.content.pm.PackageManager.NameNotFoundException;
     58 import android.content.pm.ResolveInfo;
     59 import android.content.pm.ServiceInfo;
     60 import android.content.pm.UserInfo;
     61 import android.database.ContentObserver;
     62 import android.graphics.Bitmap;
     63 import android.media.AudioManager;
     64 import android.media.IAudioService;
     65 import android.net.ConnectivityManager;
     66 import android.net.ProxyInfo;
     67 import android.net.Uri;
     68 import android.os.AsyncTask;
     69 import android.os.Binder;
     70 import android.os.Bundle;
     71 import android.os.Environment;
     72 import android.os.FileUtils;
     73 import android.os.Handler;
     74 import android.os.IBinder;
     75 import android.os.PersistableBundle;
     76 import android.os.PowerManager;
     77 import android.os.PowerManagerInternal;
     78 import android.os.Process;
     79 import android.os.RecoverySystem;
     80 import android.os.RemoteCallback;
     81 import android.os.RemoteException;
     82 import android.os.ServiceManager;
     83 import android.os.SystemClock;
     84 import android.os.SystemProperties;
     85 import android.os.UserHandle;
     86 import android.os.UserManager;
     87 import android.os.storage.StorageManager;
     88 import android.provider.ContactsContract.QuickContact;
     89 import android.provider.ContactsInternal;
     90 import android.provider.Settings;
     91 import android.security.Credentials;
     92 import android.security.IKeyChainAliasCallback;
     93 import android.security.IKeyChainService;
     94 import android.security.KeyChain;
     95 import android.security.KeyChain.KeyChainConnection;
     96 import android.service.persistentdata.PersistentDataBlockManager;
     97 import android.text.TextUtils;
     98 import android.util.Log;
     99 import android.util.PrintWriterPrinter;
    100 import android.util.Printer;
    101 import android.util.Slog;
    102 import android.util.SparseArray;
    103 import android.util.Xml;
    104 import android.view.IWindowManager;
    105 import android.view.accessibility.AccessibilityManager;
    106 import android.view.accessibility.IAccessibilityManager;
    107 import android.view.inputmethod.InputMethodInfo;
    108 import android.view.inputmethod.InputMethodManager;
    109 
    110 import com.android.internal.R;
    111 import com.android.internal.statusbar.IStatusBarService;
    112 import com.android.internal.util.FastXmlSerializer;
    113 import com.android.internal.util.JournaledFile;
    114 import com.android.internal.util.Preconditions;
    115 import com.android.internal.util.XmlUtils;
    116 import com.android.internal.widget.LockPatternUtils;
    117 import com.android.server.LocalServices;
    118 import com.android.server.SystemService;
    119 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
    120 
    121 import org.xmlpull.v1.XmlPullParser;
    122 import org.xmlpull.v1.XmlPullParserException;
    123 import org.xmlpull.v1.XmlSerializer;
    124 
    125 import java.io.ByteArrayInputStream;
    126 import java.io.File;
    127 import java.io.FileDescriptor;
    128 import java.io.FileInputStream;
    129 import java.io.FileNotFoundException;
    130 import java.io.FileOutputStream;
    131 import java.io.IOException;
    132 import java.io.PrintWriter;
    133 import java.nio.charset.StandardCharsets;
    134 import java.security.cert.CertificateException;
    135 import java.security.cert.CertificateFactory;
    136 import java.security.cert.X509Certificate;
    137 import java.text.DateFormat;
    138 import java.util.ArrayList;
    139 import java.util.Arrays;
    140 import java.util.Collections;
    141 import java.util.Date;
    142 import java.util.HashMap;
    143 import java.util.HashSet;
    144 import java.util.List;
    145 import java.util.Map.Entry;
    146 import java.util.Set;
    147 
    148 /**
    149  * Implementation of the device policy APIs.
    150  */
    151 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
    152 
    153     private static final String LOG_TAG = "DevicePolicyManagerService";
    154 
    155     private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
    156 
    157     private static final String DEVICE_POLICIES_XML = "device_policies.xml";
    158 
    159     private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
    160 
    161     private static final String TAG_STATUS_BAR = "statusbar";
    162 
    163     private static final String ATTR_DISABLED = "disabled";
    164 
    165     private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
    166             "do-not-ask-credentials-on-boot";
    167 
    168     private static final int REQUEST_EXPIRE_PASSWORD = 5571;
    169 
    170     private static final long MS_PER_DAY = 86400 * 1000;
    171 
    172     private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
    173 
    174     protected static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
    175             = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
    176 
    177     private static final int MONITORING_CERT_NOTIFICATION_ID = R.string.ssl_ca_cert_warning;
    178     private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
    179 
    180     private static final boolean DBG = false;
    181 
    182     private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
    183     private static final String ATTR_SETUP_COMPLETE = "setup-complete";
    184     private static final String ATTR_PERMISSION_POLICY = "permission-policy";
    185 
    186     private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
    187 
    188     private static final int STATUS_BAR_DISABLE_MASK =
    189             StatusBarManager.DISABLE_EXPAND |
    190             StatusBarManager.DISABLE_NOTIFICATION_ICONS |
    191             StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
    192             StatusBarManager.DISABLE_SEARCH;
    193 
    194     private static final int STATUS_BAR_DISABLE2_MASK =
    195             StatusBarManager.DISABLE2_QUICK_SETTINGS;
    196 
    197     private static final Set<String> DEVICE_OWNER_USER_RESTRICTIONS;
    198     static {
    199         DEVICE_OWNER_USER_RESTRICTIONS = new HashSet();
    200         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_USB_FILE_TRANSFER);
    201         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_TETHERING);
    202         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_NETWORK_RESET);
    203         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_FACTORY_RESET);
    204         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADD_USER);
    205         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
    206         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
    207         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
    208         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_UNMUTE_MICROPHONE);
    209         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADJUST_VOLUME);
    210         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SMS);
    211         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_FUN);
    212         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SAFE_BOOT);
    213         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CREATE_WINDOWS);
    214     }
    215 
    216     // The following user restrictions cannot be changed by any active admin, including device
    217     // owner and profile owner.
    218     private static final Set<String> IMMUTABLE_USER_RESTRICTIONS;
    219     static {
    220         IMMUTABLE_USER_RESTRICTIONS = new HashSet();
    221         IMMUTABLE_USER_RESTRICTIONS.add(UserManager.DISALLOW_WALLPAPER);
    222     }
    223 
    224     private static final Set<String> SECURE_SETTINGS_WHITELIST;
    225     private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
    226     private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
    227     private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
    228     static {
    229         SECURE_SETTINGS_WHITELIST = new HashSet();
    230         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
    231         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
    232         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
    233 
    234         SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new HashSet();
    235         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
    236         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
    237 
    238         GLOBAL_SETTINGS_WHITELIST = new HashSet();
    239         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
    240         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
    241         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
    242         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
    243         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
    244         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
    245         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
    246         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
    247 
    248         GLOBAL_SETTINGS_DEPRECATED = new HashSet();
    249         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
    250         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
    251         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
    252         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
    253         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
    254     }
    255 
    256     // Keyguard features that when set of a profile will affect the profiles
    257     // parent user.
    258     private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
    259             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
    260             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
    261 
    262     // Keyguard features that are allowed to be set on a managed profile
    263     private static final int PROFILE_KEYGUARD_FEATURES =
    264             PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
    265             | DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
    266 
    267     final Context mContext;
    268     final UserManager mUserManager;
    269     final PowerManager.WakeLock mWakeLock;
    270 
    271     final LocalService mLocalService;
    272 
    273     final PowerManager mPowerManager;
    274     final PowerManagerInternal mPowerManagerInternal;
    275 
    276     IWindowManager mIWindowManager;
    277     NotificationManager mNotificationManager;
    278 
    279     // Stores and loads state on device and profile owners.
    280     private DeviceOwner mDeviceOwner;
    281 
    282     private final Binder mToken = new Binder();
    283 
    284     /**
    285      * Whether or not device admin feature is supported. If it isn't return defaults for all
    286      * public methods.
    287      */
    288     private boolean mHasFeature;
    289 
    290     public static final class Lifecycle extends SystemService {
    291         private DevicePolicyManagerService mService;
    292 
    293         public Lifecycle(Context context) {
    294             super(context);
    295             mService = new DevicePolicyManagerService(context);
    296         }
    297 
    298         @Override
    299         public void onStart() {
    300             publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
    301         }
    302 
    303         @Override
    304         public void onBootPhase(int phase) {
    305             if (phase == PHASE_LOCK_SETTINGS_READY) {
    306                 mService.systemReady();
    307             }
    308         }
    309     }
    310 
    311     public static class DevicePolicyData {
    312         int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
    313         int mActivePasswordLength = 0;
    314         int mActivePasswordUpperCase = 0;
    315         int mActivePasswordLowerCase = 0;
    316         int mActivePasswordLetters = 0;
    317         int mActivePasswordNumeric = 0;
    318         int mActivePasswordSymbols = 0;
    319         int mActivePasswordNonLetter = 0;
    320         int mFailedPasswordAttempts = 0;
    321 
    322         int mUserHandle;
    323         int mPasswordOwner = -1;
    324         long mLastMaximumTimeToLock = -1;
    325         boolean mUserSetupComplete = false;
    326         int mPermissionPolicy;
    327 
    328         final HashMap<ComponentName, ActiveAdmin> mAdminMap = new HashMap<>();
    329         final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
    330         final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
    331 
    332         // This is the list of component allowed to start lock task mode.
    333         List<String> mLockTaskPackages = new ArrayList<>();
    334 
    335         boolean mStatusBarDisabled = false;
    336 
    337         ComponentName mRestrictionsProvider;
    338 
    339         String mDelegatedCertInstallerPackage;
    340 
    341         boolean doNotAskCredentialsOnBoot = false;
    342 
    343         public DevicePolicyData(int userHandle) {
    344             mUserHandle = userHandle;
    345         }
    346     }
    347 
    348     final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
    349 
    350     Handler mHandler = new Handler();
    351 
    352     BroadcastReceiver mReceiver = new BroadcastReceiver() {
    353         @Override
    354         public void onReceive(Context context, Intent intent) {
    355             final String action = intent.getAction();
    356             final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
    357                     getSendingUserId());
    358             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
    359                     || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
    360                 if (DBG) Slog.v(LOG_TAG, "Sending password expiration notifications for action "
    361                         + action + " for user " + userHandle);
    362                 mHandler.post(new Runnable() {
    363                     @Override
    364                     public void run() {
    365                         handlePasswordExpirationNotification(userHandle);
    366                     }
    367                 });
    368             }
    369             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
    370                     || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
    371                 new MonitoringCertNotificationTask().execute(intent);
    372             }
    373             if (Intent.ACTION_USER_REMOVED.equals(action)) {
    374                 removeUserData(userHandle);
    375             } else if (Intent.ACTION_USER_STARTED.equals(action)
    376                     || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
    377 
    378                 if (Intent.ACTION_USER_STARTED.equals(action)) {
    379                     // Reset the policy data
    380                     synchronized (DevicePolicyManagerService.this) {
    381                         mUserData.remove(userHandle);
    382                     }
    383                 }
    384                 handlePackagesChanged(null /* check all admins */, userHandle);
    385             } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
    386                     || (Intent.ACTION_PACKAGE_ADDED.equals(action)
    387                             && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
    388                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
    389             } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
    390                     && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
    391                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
    392             } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
    393                 clearWipeProfileNotification();
    394             }
    395         }
    396     };
    397 
    398     static class ActiveAdmin {
    399         private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
    400         private static final String TAG_DISABLE_CAMERA = "disable-camera";
    401         private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
    402         private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
    403                 = "disable-bt-contacts-sharing";
    404         private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
    405         private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
    406         private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
    407         private static final String TAG_ACCOUNT_TYPE = "account-type";
    408         private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
    409                 = "permitted-accessiblity-services";
    410         private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
    411         private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
    412         private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
    413         private static final String TAG_TRUST_AGENT_COMPONENT = "component";
    414         private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
    415         private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
    416         private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
    417         private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
    418         private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
    419         private static final String TAG_PERMITTED_IMES = "permitted-imes";
    420         private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
    421         private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
    422         private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
    423         private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
    424         private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
    425         private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
    426         private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
    427         private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
    428         private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
    429         private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
    430         private static final String ATTR_VALUE = "value";
    431         private static final String TAG_PASSWORD_QUALITY = "password-quality";
    432         private static final String TAG_POLICIES = "policies";
    433         private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
    434                 "cross-profile-widget-providers";
    435         private static final String TAG_PROVIDER = "provider";
    436         private static final String TAG_PACKAGE_LIST_ITEM  = "item";
    437 
    438         final DeviceAdminInfo info;
    439 
    440         int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
    441 
    442         static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
    443         int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
    444 
    445         static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
    446         int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
    447 
    448         static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
    449         int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
    450 
    451         static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
    452         int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
    453 
    454         static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
    455         int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
    456 
    457         static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
    458         int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
    459 
    460         static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
    461         int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
    462 
    463         static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
    464         int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
    465 
    466         static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
    467         long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
    468 
    469         static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
    470         int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
    471 
    472         static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
    473         long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
    474 
    475         static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
    476         long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
    477 
    478         static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
    479 
    480         int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
    481 
    482         boolean encryptionRequested = false;
    483         boolean disableCamera = false;
    484         boolean disableCallerId = false;
    485         boolean disableBluetoothContactSharing = true;
    486         boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
    487         boolean requireAutoTime = false; // Can only be set by a device owner.
    488 
    489         static class TrustAgentInfo {
    490             public PersistableBundle options;
    491             TrustAgentInfo(PersistableBundle bundle) {
    492                 options = bundle;
    493             }
    494         }
    495 
    496         Set<String> accountTypesWithManagementDisabled = new HashSet<String>();
    497 
    498         // The list of permitted accessibility services package namesas set by a profile
    499         // or device owner. Null means all accessibility services are allowed, empty means
    500         // none except system services are allowed.
    501         List<String> permittedAccessiblityServices;
    502 
    503         // The list of permitted input methods package names as set by a profile or device owner.
    504         // Null means all input methods are allowed, empty means none except system imes are
    505         // allowed.
    506         List<String> permittedInputMethods;
    507 
    508         // TODO: review implementation decisions with frameworks team
    509         boolean specifiesGlobalProxy = false;
    510         String globalProxySpec = null;
    511         String globalProxyExclusionList = null;
    512 
    513         HashMap<String, TrustAgentInfo> trustAgentInfos = new HashMap<String, TrustAgentInfo>();
    514 
    515         List<String> crossProfileWidgetProviders;
    516 
    517         ActiveAdmin(DeviceAdminInfo _info) {
    518             info = _info;
    519         }
    520 
    521         int getUid() { return info.getActivityInfo().applicationInfo.uid; }
    522 
    523         public UserHandle getUserHandle() {
    524             return new UserHandle(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
    525         }
    526 
    527         void writeToXml(XmlSerializer out)
    528                 throws IllegalArgumentException, IllegalStateException, IOException {
    529             out.startTag(null, TAG_POLICIES);
    530             info.writePoliciesToXml(out);
    531             out.endTag(null, TAG_POLICIES);
    532             if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
    533                 out.startTag(null, TAG_PASSWORD_QUALITY);
    534                 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
    535                 out.endTag(null, TAG_PASSWORD_QUALITY);
    536                 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
    537                     out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
    538                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
    539                     out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
    540                 }
    541                 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
    542                     out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
    543                     out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
    544                     out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
    545                 }
    546                 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
    547                     out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
    548                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
    549                     out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
    550                 }
    551                 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
    552                     out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
    553                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
    554                     out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
    555                 }
    556                 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
    557                     out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
    558                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
    559                     out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
    560                 }
    561                 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
    562                     out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
    563                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
    564                     out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
    565                 }
    566                 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
    567                     out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
    568                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
    569                     out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
    570                 }
    571                 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
    572                     out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
    573                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
    574                     out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
    575                 }
    576             }
    577             if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
    578                 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
    579                 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
    580                 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
    581             }
    582             if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
    583                 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
    584                 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
    585                 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
    586             }
    587             if (specifiesGlobalProxy) {
    588                 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
    589                 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
    590                 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
    591                 if (globalProxySpec != null) {
    592                     out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
    593                     out.attribute(null, ATTR_VALUE, globalProxySpec);
    594                     out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
    595                 }
    596                 if (globalProxyExclusionList != null) {
    597                     out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
    598                     out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
    599                     out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
    600                 }
    601             }
    602             if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
    603                 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
    604                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
    605                 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
    606             }
    607             if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
    608                 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
    609                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
    610                 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
    611             }
    612             if (encryptionRequested) {
    613                 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
    614                 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
    615                 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
    616             }
    617             if (disableCamera) {
    618                 out.startTag(null, TAG_DISABLE_CAMERA);
    619                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
    620                 out.endTag(null, TAG_DISABLE_CAMERA);
    621             }
    622             if (disableCallerId) {
    623                 out.startTag(null, TAG_DISABLE_CALLER_ID);
    624                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
    625                 out.endTag(null, TAG_DISABLE_CALLER_ID);
    626             }
    627             if (disableBluetoothContactSharing) {
    628                 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
    629                 out.attribute(null, ATTR_VALUE,
    630                         Boolean.toString(disableBluetoothContactSharing));
    631                 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
    632             }
    633             if (disableScreenCapture) {
    634                 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
    635                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
    636                 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
    637             }
    638             if (requireAutoTime) {
    639                 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
    640                 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
    641                 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
    642             }
    643             if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
    644                 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
    645                 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
    646                 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
    647             }
    648             if (!accountTypesWithManagementDisabled.isEmpty()) {
    649                 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
    650                 for (String ac : accountTypesWithManagementDisabled) {
    651                     out.startTag(null, TAG_ACCOUNT_TYPE);
    652                     out.attribute(null, ATTR_VALUE, ac);
    653                     out.endTag(null, TAG_ACCOUNT_TYPE);
    654                 }
    655                 out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
    656             }
    657             if (!trustAgentInfos.isEmpty()) {
    658                 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
    659                 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
    660                 for (Entry<String, TrustAgentInfo> entry : set) {
    661                     TrustAgentInfo trustAgentInfo = entry.getValue();
    662                     out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
    663                     out.attribute(null, ATTR_VALUE, entry.getKey());
    664                     if (trustAgentInfo.options != null) {
    665                         out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
    666                         try {
    667                             trustAgentInfo.options.saveToXml(out);
    668                         } catch (XmlPullParserException e) {
    669                             Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
    670                         }
    671                         out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
    672                     }
    673                     out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
    674                 }
    675                 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
    676             }
    677             if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
    678                 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
    679                 final int providerCount = crossProfileWidgetProviders.size();
    680                 for (int i = 0; i < providerCount; i++) {
    681                     String provider = crossProfileWidgetProviders.get(i);
    682                     out.startTag(null, TAG_PROVIDER);
    683                     out.attribute(null, ATTR_VALUE, provider);
    684                     out.endTag(null, TAG_PROVIDER);
    685                 }
    686                 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
    687             }
    688             writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
    689                     permittedAccessiblityServices);
    690             writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
    691         }
    692 
    693         void writePackageListToXml(XmlSerializer out, String outerTag,
    694                 List<String> packageList)
    695                 throws IllegalArgumentException, IllegalStateException, IOException {
    696             if (packageList == null) {
    697                 return;
    698             }
    699 
    700             out.startTag(null, outerTag);
    701             for (String packageName : packageList) {
    702                 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
    703                 out.attribute(null, ATTR_VALUE, packageName);
    704                 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
    705             }
    706             out.endTag(null, outerTag);
    707         }
    708 
    709         void readFromXml(XmlPullParser parser)
    710                 throws XmlPullParserException, IOException {
    711             int outerDepth = parser.getDepth();
    712             int type;
    713             while ((type=parser.next()) != END_DOCUMENT
    714                    && (type != END_TAG || parser.getDepth() > outerDepth)) {
    715                 if (type == END_TAG || type == TEXT) {
    716                     continue;
    717                 }
    718                 String tag = parser.getName();
    719                 if (TAG_POLICIES.equals(tag)) {
    720                     info.readPoliciesFromXml(parser);
    721                 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
    722                     passwordQuality = Integer.parseInt(
    723                             parser.getAttributeValue(null, ATTR_VALUE));
    724                 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
    725                     minimumPasswordLength = Integer.parseInt(
    726                             parser.getAttributeValue(null, ATTR_VALUE));
    727                 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
    728                     passwordHistoryLength = Integer.parseInt(
    729                             parser.getAttributeValue(null, ATTR_VALUE));
    730                 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
    731                     minimumPasswordUpperCase = Integer.parseInt(
    732                             parser.getAttributeValue(null, ATTR_VALUE));
    733                 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
    734                     minimumPasswordLowerCase = Integer.parseInt(
    735                             parser.getAttributeValue(null, ATTR_VALUE));
    736                 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
    737                     minimumPasswordLetters = Integer.parseInt(
    738                             parser.getAttributeValue(null, ATTR_VALUE));
    739                 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
    740                     minimumPasswordNumeric = Integer.parseInt(
    741                             parser.getAttributeValue(null, ATTR_VALUE));
    742                 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
    743                     minimumPasswordSymbols = Integer.parseInt(
    744                             parser.getAttributeValue(null, ATTR_VALUE));
    745                 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
    746                     minimumPasswordNonLetter = Integer.parseInt(
    747                             parser.getAttributeValue(null, ATTR_VALUE));
    748                 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
    749                     maximumTimeToUnlock = Long.parseLong(
    750                             parser.getAttributeValue(null, ATTR_VALUE));
    751                 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
    752                     maximumFailedPasswordsForWipe = Integer.parseInt(
    753                             parser.getAttributeValue(null, ATTR_VALUE));
    754                 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
    755                     specifiesGlobalProxy = Boolean.parseBoolean(
    756                             parser.getAttributeValue(null, ATTR_VALUE));
    757                 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
    758                     globalProxySpec =
    759                         parser.getAttributeValue(null, ATTR_VALUE);
    760                 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
    761                     globalProxyExclusionList =
    762                         parser.getAttributeValue(null, ATTR_VALUE);
    763                 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
    764                     passwordExpirationTimeout = Long.parseLong(
    765                             parser.getAttributeValue(null, ATTR_VALUE));
    766                 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
    767                     passwordExpirationDate = Long.parseLong(
    768                             parser.getAttributeValue(null, ATTR_VALUE));
    769                 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
    770                     encryptionRequested = Boolean.parseBoolean(
    771                             parser.getAttributeValue(null, ATTR_VALUE));
    772                 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
    773                     disableCamera = Boolean.parseBoolean(
    774                             parser.getAttributeValue(null, ATTR_VALUE));
    775                 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
    776                     disableCallerId = Boolean.parseBoolean(
    777                             parser.getAttributeValue(null, ATTR_VALUE));
    778                 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
    779                     disableBluetoothContactSharing = Boolean.parseBoolean(parser
    780                             .getAttributeValue(null, ATTR_VALUE));
    781                 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
    782                     disableScreenCapture = Boolean.parseBoolean(
    783                             parser.getAttributeValue(null, ATTR_VALUE));
    784                 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
    785                     requireAutoTime= Boolean.parseBoolean(
    786                             parser.getAttributeValue(null, ATTR_VALUE));
    787                 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
    788                     disabledKeyguardFeatures = Integer.parseInt(
    789                             parser.getAttributeValue(null, ATTR_VALUE));
    790                 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
    791                     accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
    792                 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
    793                     trustAgentInfos = getAllTrustAgentInfos(parser, tag);
    794                 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
    795                     crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
    796                 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
    797                     permittedAccessiblityServices = readPackageList(parser, tag);
    798                 } else if (TAG_PERMITTED_IMES.equals(tag)) {
    799                     permittedInputMethods = readPackageList(parser, tag);
    800                 } else {
    801                     Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
    802                     XmlUtils.skipCurrentTag(parser);
    803                 }
    804             }
    805         }
    806 
    807         private List<String> readPackageList(XmlPullParser parser,
    808                 String tag) throws XmlPullParserException, IOException {
    809             List<String> result = new ArrayList<String>();
    810             int outerDepth = parser.getDepth();
    811             int outerType;
    812             while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
    813                     && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
    814                 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
    815                     continue;
    816                 }
    817                 String outerTag = parser.getName();
    818                 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
    819                     String packageName = parser.getAttributeValue(null, ATTR_VALUE);
    820                     if (packageName != null) {
    821                         result.add(packageName);
    822                     } else {
    823                         Slog.w(LOG_TAG, "Package name missing under " + outerTag);
    824                     }
    825                 } else {
    826                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
    827                 }
    828             }
    829             return result;
    830         }
    831 
    832         private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
    833                 throws XmlPullParserException, IOException {
    834             int outerDepthDAM = parser.getDepth();
    835             int typeDAM;
    836             Set<String> result = new HashSet<String>();
    837             while ((typeDAM=parser.next()) != END_DOCUMENT
    838                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
    839                 if (typeDAM == END_TAG || typeDAM == TEXT) {
    840                     continue;
    841                 }
    842                 String tagDAM = parser.getName();
    843                 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
    844                     result.add(parser.getAttributeValue(null, ATTR_VALUE));
    845                 } else {
    846                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
    847                 }
    848             }
    849             return result;
    850         }
    851 
    852         private HashMap<String, TrustAgentInfo> getAllTrustAgentInfos(
    853                 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
    854             int outerDepthDAM = parser.getDepth();
    855             int typeDAM;
    856             HashMap<String, TrustAgentInfo> result = new HashMap<String, TrustAgentInfo>();
    857             while ((typeDAM=parser.next()) != END_DOCUMENT
    858                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
    859                 if (typeDAM == END_TAG || typeDAM == TEXT) {
    860                     continue;
    861                 }
    862                 String tagDAM = parser.getName();
    863                 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
    864                     final String component = parser.getAttributeValue(null, ATTR_VALUE);
    865                     final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
    866                     result.put(component, trustAgentInfo);
    867                 } else {
    868                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
    869                 }
    870             }
    871             return result;
    872         }
    873 
    874         private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
    875                 throws XmlPullParserException, IOException  {
    876             int outerDepthDAM = parser.getDepth();
    877             int typeDAM;
    878             TrustAgentInfo result = new TrustAgentInfo(null);
    879             while ((typeDAM=parser.next()) != END_DOCUMENT
    880                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
    881                 if (typeDAM == END_TAG || typeDAM == TEXT) {
    882                     continue;
    883                 }
    884                 String tagDAM = parser.getName();
    885                 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
    886                     PersistableBundle bundle = new PersistableBundle();
    887                     bundle.restoreFromXml(parser);
    888                     result.options = bundle;
    889                 } else {
    890                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
    891                 }
    892             }
    893             return result;
    894         }
    895 
    896         private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
    897                 throws XmlPullParserException, IOException  {
    898             int outerDepthDAM = parser.getDepth();
    899             int typeDAM;
    900             ArrayList<String> result = null;
    901             while ((typeDAM=parser.next()) != END_DOCUMENT
    902                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
    903                 if (typeDAM == END_TAG || typeDAM == TEXT) {
    904                     continue;
    905                 }
    906                 String tagDAM = parser.getName();
    907                 if (TAG_PROVIDER.equals(tagDAM)) {
    908                     final String provider = parser.getAttributeValue(null, ATTR_VALUE);
    909                     if (result == null) {
    910                         result = new ArrayList<>();
    911                     }
    912                     result.add(provider);
    913                 } else {
    914                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
    915                 }
    916             }
    917             return result;
    918         }
    919 
    920         void dump(String prefix, PrintWriter pw) {
    921             pw.print(prefix); pw.print("uid="); pw.println(getUid());
    922             pw.print(prefix); pw.println("policies:");
    923             ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
    924             if (pols != null) {
    925                 for (int i=0; i<pols.size(); i++) {
    926                     pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
    927                 }
    928             }
    929             pw.print(prefix); pw.print("passwordQuality=0x");
    930                     pw.println(Integer.toHexString(passwordQuality));
    931             pw.print(prefix); pw.print("minimumPasswordLength=");
    932                     pw.println(minimumPasswordLength);
    933             pw.print(prefix); pw.print("passwordHistoryLength=");
    934                     pw.println(passwordHistoryLength);
    935             pw.print(prefix); pw.print("minimumPasswordUpperCase=");
    936                     pw.println(minimumPasswordUpperCase);
    937             pw.print(prefix); pw.print("minimumPasswordLowerCase=");
    938                     pw.println(minimumPasswordLowerCase);
    939             pw.print(prefix); pw.print("minimumPasswordLetters=");
    940                     pw.println(minimumPasswordLetters);
    941             pw.print(prefix); pw.print("minimumPasswordNumeric=");
    942                     pw.println(minimumPasswordNumeric);
    943             pw.print(prefix); pw.print("minimumPasswordSymbols=");
    944                     pw.println(minimumPasswordSymbols);
    945             pw.print(prefix); pw.print("minimumPasswordNonLetter=");
    946                     pw.println(minimumPasswordNonLetter);
    947             pw.print(prefix); pw.print("maximumTimeToUnlock=");
    948                     pw.println(maximumTimeToUnlock);
    949             pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
    950                     pw.println(maximumFailedPasswordsForWipe);
    951             pw.print(prefix); pw.print("specifiesGlobalProxy=");
    952                     pw.println(specifiesGlobalProxy);
    953             pw.print(prefix); pw.print("passwordExpirationTimeout=");
    954                     pw.println(passwordExpirationTimeout);
    955             pw.print(prefix); pw.print("passwordExpirationDate=");
    956                     pw.println(passwordExpirationDate);
    957             if (globalProxySpec != null) {
    958                 pw.print(prefix); pw.print("globalProxySpec=");
    959                         pw.println(globalProxySpec);
    960             }
    961             if (globalProxyExclusionList != null) {
    962                 pw.print(prefix); pw.print("globalProxyEclusionList=");
    963                         pw.println(globalProxyExclusionList);
    964             }
    965             pw.print(prefix); pw.print("encryptionRequested=");
    966                     pw.println(encryptionRequested);
    967             pw.print(prefix); pw.print("disableCamera=");
    968                     pw.println(disableCamera);
    969             pw.print(prefix); pw.print("disableCallerId=");
    970                     pw.println(disableCallerId);
    971             pw.print(prefix); pw.print("disableBluetoothContactSharing=");
    972                     pw.println(disableBluetoothContactSharing);
    973             pw.print(prefix); pw.print("disableScreenCapture=");
    974                     pw.println(disableScreenCapture);
    975             pw.print(prefix); pw.print("requireAutoTime=");
    976                     pw.println(requireAutoTime);
    977             pw.print(prefix); pw.print("disabledKeyguardFeatures=");
    978                     pw.println(disabledKeyguardFeatures);
    979             pw.print(prefix); pw.print("crossProfileWidgetProviders=");
    980                     pw.println(crossProfileWidgetProviders);
    981             if (!(permittedAccessiblityServices == null)) {
    982                 pw.print(prefix); pw.print("permittedAccessibilityServices=");
    983                         pw.println(permittedAccessiblityServices.toString());
    984             }
    985             if (!(permittedInputMethods == null)) {
    986                 pw.print(prefix); pw.print("permittedInputMethods=");
    987                         pw.println(permittedInputMethods.toString());
    988             }
    989         }
    990     }
    991 
    992     private void handlePackagesChanged(String packageName, int userHandle) {
    993         boolean removed = false;
    994         if (DBG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
    995         DevicePolicyData policy = getUserData(userHandle);
    996         IPackageManager pm = AppGlobals.getPackageManager();
    997         synchronized (this) {
    998             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
    999                 ActiveAdmin aa = policy.mAdminList.get(i);
   1000                 try {
   1001                     // If we're checking all packages or if the specific one we're checking matches,
   1002                     // then check if the package and receiver still exist.
   1003                     final String adminPackage = aa.info.getPackageName();
   1004                     if (packageName == null || packageName.equals(adminPackage)) {
   1005                         if (pm.getPackageInfo(adminPackage, 0, userHandle) == null
   1006                                 || pm.getReceiverInfo(aa.info.getComponent(), 0, userHandle)
   1007                                     == null) {
   1008                             removed = true;
   1009                             policy.mAdminList.remove(i);
   1010                             policy.mAdminMap.remove(aa.info.getComponent());
   1011                         }
   1012                     }
   1013                 } catch (RemoteException re) {
   1014                     // Shouldn't happen
   1015                 }
   1016             }
   1017             if (removed) {
   1018                 validatePasswordOwnerLocked(policy);
   1019                 syncDeviceCapabilitiesLocked(policy);
   1020                 saveSettingsLocked(policy.mUserHandle);
   1021             }
   1022 
   1023             if (policy.mDelegatedCertInstallerPackage != null &&
   1024                     (packageName == null
   1025                     || packageName.equals(policy.mDelegatedCertInstallerPackage))) {
   1026                 try {
   1027                     // Check if delegated cert installer package is removed.
   1028                     if (pm.getPackageInfo(
   1029                             policy.mDelegatedCertInstallerPackage, 0, userHandle) == null) {
   1030                         policy.mDelegatedCertInstallerPackage = null;
   1031                         saveSettingsLocked(policy.mUserHandle);
   1032                     }
   1033                 } catch (RemoteException e) {
   1034                     // Shouldn't happen
   1035                 }
   1036             }
   1037         }
   1038     }
   1039 
   1040     /**
   1041      * Instantiates the service.
   1042      */
   1043     public DevicePolicyManagerService(Context context) {
   1044         mContext = context;
   1045         mUserManager = UserManager.get(mContext);
   1046         mHasFeature = context.getPackageManager().hasSystemFeature(
   1047                 PackageManager.FEATURE_DEVICE_ADMIN);
   1048         mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
   1049         mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
   1050         mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DPM");
   1051         mLocalService = new LocalService();
   1052         if (!mHasFeature) {
   1053             // Skip the rest of the initialization
   1054             return;
   1055         }
   1056         IntentFilter filter = new IntentFilter();
   1057         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
   1058         filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
   1059         filter.addAction(Intent.ACTION_USER_REMOVED);
   1060         filter.addAction(Intent.ACTION_USER_STARTED);
   1061         filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
   1062         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
   1063         context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
   1064         filter = new IntentFilter();
   1065         filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
   1066         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
   1067         filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
   1068         filter.addAction(Intent.ACTION_PACKAGE_ADDED);
   1069         filter.addDataScheme("package");
   1070         context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
   1071         filter = new IntentFilter();
   1072         filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
   1073         context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
   1074 
   1075         LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
   1076     }
   1077 
   1078     /**
   1079      * Creates and loads the policy data from xml.
   1080      * @param userHandle the user for whom to load the policy data
   1081      * @return
   1082      */
   1083     DevicePolicyData getUserData(int userHandle) {
   1084         synchronized (this) {
   1085             DevicePolicyData policy = mUserData.get(userHandle);
   1086             if (policy == null) {
   1087                 policy = new DevicePolicyData(userHandle);
   1088                 mUserData.append(userHandle, policy);
   1089                 loadSettingsLocked(policy, userHandle);
   1090             }
   1091             return policy;
   1092         }
   1093     }
   1094 
   1095     /**
   1096      * Creates and loads the policy data from xml for data that is shared between
   1097      * various profiles of a user. In contrast to {@link #getUserData(int)}
   1098      * it allows access to data of users other than the calling user.
   1099      *
   1100      * This function should only be used for shared data, e.g. everything regarding
   1101      * passwords and should be removed once multiple screen locks are present.
   1102      * @param userHandle the user for whom to load the policy data
   1103      * @return
   1104      */
   1105     DevicePolicyData getUserDataUnchecked(int userHandle) {
   1106         long ident = Binder.clearCallingIdentity();
   1107         try {
   1108             return getUserData(userHandle);
   1109         } finally {
   1110             Binder.restoreCallingIdentity(ident);
   1111         }
   1112     }
   1113 
   1114     void removeUserData(int userHandle) {
   1115         synchronized (this) {
   1116             if (userHandle == UserHandle.USER_OWNER) {
   1117                 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
   1118                 return;
   1119             }
   1120             if (mDeviceOwner != null) {
   1121                 mDeviceOwner.removeProfileOwner(userHandle);
   1122                 mDeviceOwner.writeOwnerFile();
   1123             }
   1124 
   1125             DevicePolicyData policy = mUserData.get(userHandle);
   1126             if (policy != null) {
   1127                 mUserData.remove(userHandle);
   1128             }
   1129             File policyFile = new File(Environment.getUserSystemDirectory(userHandle),
   1130                     DEVICE_POLICIES_XML);
   1131             policyFile.delete();
   1132             Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
   1133         }
   1134         updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
   1135     }
   1136 
   1137     void loadDeviceOwner() {
   1138         synchronized (this) {
   1139             mDeviceOwner = DeviceOwner.load();
   1140             updateDeviceOwnerLocked();
   1141         }
   1142     }
   1143 
   1144     /**
   1145      * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
   1146      * reminders.  Clears alarm if no expirations are configured.
   1147      */
   1148     protected void setExpirationAlarmCheckLocked(Context context, DevicePolicyData policy) {
   1149         final long expiration = getPasswordExpirationLocked(null, policy.mUserHandle);
   1150         final long now = System.currentTimeMillis();
   1151         final long timeToExpire = expiration - now;
   1152         final long alarmTime;
   1153         if (expiration == 0) {
   1154             // No expirations are currently configured:  Cancel alarm.
   1155             alarmTime = 0;
   1156         } else if (timeToExpire <= 0) {
   1157             // The password has already expired:  Repeat every 24 hours.
   1158             alarmTime = now + MS_PER_DAY;
   1159         } else {
   1160             // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
   1161             // the expiration time.
   1162             long alarmInterval = timeToExpire % MS_PER_DAY;
   1163             if (alarmInterval == 0) {
   1164                 alarmInterval = MS_PER_DAY;
   1165             }
   1166             alarmTime = now + alarmInterval;
   1167         }
   1168 
   1169         long token = Binder.clearCallingIdentity();
   1170         try {
   1171             AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   1172             PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
   1173                     new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
   1174                     PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
   1175                     new UserHandle(policy.mUserHandle));
   1176             am.cancel(pi);
   1177             if (alarmTime != 0) {
   1178                 am.set(AlarmManager.RTC, alarmTime, pi);
   1179             }
   1180         } finally {
   1181             Binder.restoreCallingIdentity(token);
   1182         }
   1183     }
   1184 
   1185     private IWindowManager getWindowManager() {
   1186         if (mIWindowManager == null) {
   1187             IBinder b = ServiceManager.getService(Context.WINDOW_SERVICE);
   1188             mIWindowManager = IWindowManager.Stub.asInterface(b);
   1189         }
   1190         return mIWindowManager;
   1191     }
   1192 
   1193     private NotificationManager getNotificationManager() {
   1194         if (mNotificationManager == null) {
   1195             mNotificationManager =
   1196                     (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
   1197         }
   1198         return mNotificationManager;
   1199     }
   1200 
   1201     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
   1202         ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
   1203         if (admin != null
   1204                 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
   1205                 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
   1206             return admin;
   1207         }
   1208         return null;
   1209     }
   1210 
   1211     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
   1212             throws SecurityException {
   1213         final int callingUid = Binder.getCallingUid();
   1214 
   1215         ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
   1216         if (result != null) {
   1217             return result;
   1218         }
   1219 
   1220         if (who != null) {
   1221             final int userId = UserHandle.getUserId(callingUid);
   1222             final DevicePolicyData policy = getUserData(userId);
   1223             ActiveAdmin admin = policy.mAdminMap.get(who);
   1224             if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
   1225                 throw new SecurityException("Admin " + admin.info.getComponent()
   1226                          + " does not own the device");
   1227             }
   1228             if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
   1229                 throw new SecurityException("Admin " + admin.info.getComponent()
   1230                         + " does not own the profile");
   1231             }
   1232             throw new SecurityException("Admin " + admin.info.getComponent()
   1233                     + " did not specify uses-policy for: "
   1234                     + admin.info.getTagForPolicy(reqPolicy));
   1235         } else {
   1236             throw new SecurityException("No active admin owned by uid "
   1237                     + Binder.getCallingUid() + " for policy #" + reqPolicy);
   1238         }
   1239     }
   1240 
   1241     private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
   1242             int uid) {
   1243         // Try to find an admin which can use reqPolicy
   1244         final int userId = UserHandle.getUserId(uid);
   1245         final DevicePolicyData policy = getUserData(userId);
   1246         if (who != null) {
   1247             ActiveAdmin admin = policy.mAdminMap.get(who);
   1248             if (admin == null) {
   1249                 throw new SecurityException("No active admin " + who);
   1250             }
   1251             if (admin.getUid() != uid) {
   1252                 throw new SecurityException("Admin " + who + " is not owned by uid "
   1253                         + Binder.getCallingUid());
   1254             }
   1255             if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
   1256                 return admin;
   1257             }
   1258         } else {
   1259             for (ActiveAdmin admin : policy.mAdminList) {
   1260                 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
   1261                         userId)) {
   1262                     return admin;
   1263                 }
   1264             }
   1265         }
   1266 
   1267         return null;
   1268     }
   1269 
   1270     private boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
   1271             int userId) {
   1272         boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
   1273         boolean ownsProfile = (getProfileOwner(userId) != null
   1274                 && getProfileOwner(userId).getPackageName()
   1275                     .equals(admin.info.getPackageName()));
   1276         boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName())
   1277                 && !hasUserSetupCompleted(userId);
   1278 
   1279         if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
   1280             if ((userId == UserHandle.USER_OWNER && (ownsDevice || ownsInitialization))
   1281                     || (ownsDevice && ownsProfile)) {
   1282                 return true;
   1283             }
   1284         } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
   1285             if ((userId == UserHandle.USER_OWNER && ownsDevice) || ownsProfile
   1286                     || ownsInitialization) {
   1287                 return true;
   1288             }
   1289         } else {
   1290             if (admin.info.usesPolicy(reqPolicy)) {
   1291                 return true;
   1292             }
   1293         }
   1294         return false;
   1295     }
   1296 
   1297     void sendAdminCommandLocked(ActiveAdmin admin, String action) {
   1298         sendAdminCommandLocked(admin, action, null);
   1299     }
   1300 
   1301     void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
   1302         sendAdminCommandLocked(admin, action, null, result);
   1303     }
   1304 
   1305     /**
   1306      * Send an update to one specific admin, get notified when that admin returns a result.
   1307      */
   1308     void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
   1309             BroadcastReceiver result) {
   1310         Intent intent = new Intent(action);
   1311         intent.setComponent(admin.info.getComponent());
   1312         if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
   1313             intent.putExtra("expiration", admin.passwordExpirationDate);
   1314         }
   1315         if (adminExtras != null) {
   1316             intent.putExtras(adminExtras);
   1317         }
   1318         if (result != null) {
   1319             mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
   1320                     null, result, mHandler, Activity.RESULT_OK, null, null);
   1321         } else {
   1322             mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
   1323         }
   1324     }
   1325 
   1326     /**
   1327      * Send an update to all admins of a user that enforce a specified policy.
   1328      */
   1329     void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
   1330         final DevicePolicyData policy = getUserData(userHandle);
   1331         final int count = policy.mAdminList.size();
   1332         if (count > 0) {
   1333             for (int i = 0; i < count; i++) {
   1334                 final ActiveAdmin admin = policy.mAdminList.get(i);
   1335                 if (admin.info.usesPolicy(reqPolicy)) {
   1336                     sendAdminCommandLocked(admin, action);
   1337                 }
   1338             }
   1339         }
   1340     }
   1341 
   1342     /**
   1343      * Send an update intent to all admins of a user and its profiles. Only send to admins that
   1344      * enforce a specified policy.
   1345      */
   1346     private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
   1347             int userHandle) {
   1348         List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   1349         for (UserInfo ui : profiles) {
   1350             int id = ui.id;
   1351             sendAdminCommandLocked(action, reqPolicy, id);
   1352         }
   1353     }
   1354 
   1355     void removeActiveAdminLocked(final ComponentName adminReceiver, int userHandle) {
   1356         final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
   1357         if (admin != null) {
   1358             synchronized (this) {
   1359                 getUserData(userHandle).mRemovingAdmins.add(adminReceiver);
   1360             }
   1361             sendAdminCommandLocked(admin,
   1362                     DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
   1363                     new BroadcastReceiver() {
   1364                         @Override
   1365                         public void onReceive(Context context, Intent intent) {
   1366                             synchronized (DevicePolicyManagerService.this) {
   1367                                 int userHandle = admin.getUserHandle().getIdentifier();
   1368                                 DevicePolicyData policy = getUserData(userHandle);
   1369                                 boolean doProxyCleanup = admin.info.usesPolicy(
   1370                                         DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
   1371                                 policy.mAdminList.remove(admin);
   1372                                 policy.mAdminMap.remove(adminReceiver);
   1373                                 validatePasswordOwnerLocked(policy);
   1374                                 syncDeviceCapabilitiesLocked(policy);
   1375                                 if (doProxyCleanup) {
   1376                                     resetGlobalProxyLocked(getUserData(userHandle));
   1377                                 }
   1378                                 saveSettingsLocked(userHandle);
   1379                                 updateMaximumTimeToLockLocked(policy);
   1380                                 policy.mRemovingAdmins.remove(adminReceiver);
   1381                             }
   1382                         }
   1383                     });
   1384         }
   1385     }
   1386 
   1387     public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle) {
   1388         if (!mHasFeature) {
   1389             return null;
   1390         }
   1391         enforceCrossUserPermission(userHandle);
   1392         Intent resolveIntent = new Intent();
   1393         resolveIntent.setComponent(adminName);
   1394         List<ResolveInfo> infos = mContext.getPackageManager().queryBroadcastReceivers(
   1395                 resolveIntent,
   1396                 PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
   1397                 userHandle);
   1398         if (infos == null || infos.size() <= 0) {
   1399             throw new IllegalArgumentException("Unknown admin: " + adminName);
   1400         }
   1401 
   1402         try {
   1403             return new DeviceAdminInfo(mContext, infos.get(0));
   1404         } catch (XmlPullParserException e) {
   1405             Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
   1406                     e);
   1407             return null;
   1408         } catch (IOException e) {
   1409             Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
   1410                     e);
   1411             return null;
   1412         }
   1413     }
   1414 
   1415     private static JournaledFile makeJournaledFile(int userHandle) {
   1416         final String base = userHandle == 0
   1417                 ? "/data/system/" + DEVICE_POLICIES_XML
   1418                 : new File(Environment.getUserSystemDirectory(userHandle), DEVICE_POLICIES_XML)
   1419                         .getAbsolutePath();
   1420         return new JournaledFile(new File(base), new File(base + ".tmp"));
   1421     }
   1422 
   1423     private void saveSettingsLocked(int userHandle) {
   1424         DevicePolicyData policy = getUserData(userHandle);
   1425         JournaledFile journal = makeJournaledFile(userHandle);
   1426         FileOutputStream stream = null;
   1427         try {
   1428             stream = new FileOutputStream(journal.chooseForWrite(), false);
   1429             XmlSerializer out = new FastXmlSerializer();
   1430             out.setOutput(stream, StandardCharsets.UTF_8.name());
   1431             out.startDocument(null, true);
   1432 
   1433             out.startTag(null, "policies");
   1434             if (policy.mRestrictionsProvider != null) {
   1435                 out.attribute(null, ATTR_PERMISSION_PROVIDER,
   1436                         policy.mRestrictionsProvider.flattenToString());
   1437             }
   1438             if (policy.mUserSetupComplete) {
   1439                 out.attribute(null, ATTR_SETUP_COMPLETE,
   1440                         Boolean.toString(true));
   1441             }
   1442             if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
   1443                 out.attribute(null, ATTR_PERMISSION_POLICY,
   1444                         Integer.toString(policy.mPermissionPolicy));
   1445             }
   1446             if (policy.mDelegatedCertInstallerPackage != null) {
   1447                 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
   1448                         policy.mDelegatedCertInstallerPackage);
   1449             }
   1450 
   1451             final int N = policy.mAdminList.size();
   1452             for (int i=0; i<N; i++) {
   1453                 ActiveAdmin ap = policy.mAdminList.get(i);
   1454                 if (ap != null) {
   1455                     out.startTag(null, "admin");
   1456                     out.attribute(null, "name", ap.info.getComponent().flattenToString());
   1457                     ap.writeToXml(out);
   1458                     out.endTag(null, "admin");
   1459                 }
   1460             }
   1461 
   1462             if (policy.mPasswordOwner >= 0) {
   1463                 out.startTag(null, "password-owner");
   1464                 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
   1465                 out.endTag(null, "password-owner");
   1466             }
   1467 
   1468             if (policy.mFailedPasswordAttempts != 0) {
   1469                 out.startTag(null, "failed-password-attempts");
   1470                 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
   1471                 out.endTag(null, "failed-password-attempts");
   1472             }
   1473 
   1474             if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
   1475                     || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
   1476                     || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
   1477                     || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
   1478                 out.startTag(null, "active-password");
   1479                 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
   1480                 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
   1481                 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
   1482                 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
   1483                 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
   1484                 out.attribute(null, "numeric", Integer
   1485                         .toString(policy.mActivePasswordNumeric));
   1486                 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
   1487                 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
   1488                 out.endTag(null, "active-password");
   1489             }
   1490 
   1491             for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
   1492                 String component = policy.mLockTaskPackages.get(i);
   1493                 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
   1494                 out.attribute(null, "name", component);
   1495                 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
   1496             }
   1497 
   1498             if (policy.mStatusBarDisabled) {
   1499                 out.startTag(null, TAG_STATUS_BAR);
   1500                 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
   1501                 out.endTag(null, TAG_STATUS_BAR);
   1502             }
   1503 
   1504             if (policy.doNotAskCredentialsOnBoot) {
   1505                 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
   1506                 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
   1507             }
   1508 
   1509             out.endTag(null, "policies");
   1510 
   1511             out.endDocument();
   1512             stream.flush();
   1513             FileUtils.sync(stream);
   1514             stream.close();
   1515             journal.commit();
   1516             sendChangedNotification(userHandle);
   1517         } catch (IOException e) {
   1518             try {
   1519                 if (stream != null) {
   1520                     stream.close();
   1521                 }
   1522             } catch (IOException ex) {
   1523                 // Ignore
   1524             }
   1525             journal.rollback();
   1526         }
   1527     }
   1528 
   1529     private void sendChangedNotification(int userHandle) {
   1530         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
   1531         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
   1532         long ident = Binder.clearCallingIdentity();
   1533         try {
   1534             mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
   1535         } finally {
   1536             Binder.restoreCallingIdentity(ident);
   1537         }
   1538     }
   1539 
   1540     private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
   1541         JournaledFile journal = makeJournaledFile(userHandle);
   1542         FileInputStream stream = null;
   1543         File file = journal.chooseForRead();
   1544         try {
   1545             stream = new FileInputStream(file);
   1546             XmlPullParser parser = Xml.newPullParser();
   1547             parser.setInput(stream, StandardCharsets.UTF_8.name());
   1548 
   1549             int type;
   1550             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
   1551                     && type != XmlPullParser.START_TAG) {
   1552             }
   1553             String tag = parser.getName();
   1554             if (!"policies".equals(tag)) {
   1555                 throw new XmlPullParserException(
   1556                         "Settings do not start with policies tag: found " + tag);
   1557             }
   1558 
   1559             // Extract the permission provider component name if available
   1560             String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
   1561             if (permissionProvider != null) {
   1562                 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
   1563             }
   1564             String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
   1565             if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
   1566                 policy.mUserSetupComplete = true;
   1567             }
   1568             String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
   1569             if (!TextUtils.isEmpty(permissionPolicy)) {
   1570                 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
   1571             }
   1572             policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
   1573                     ATTR_DELEGATED_CERT_INSTALLER);
   1574 
   1575             type = parser.next();
   1576             int outerDepth = parser.getDepth();
   1577             policy.mLockTaskPackages.clear();
   1578             policy.mAdminList.clear();
   1579             policy.mAdminMap.clear();
   1580             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
   1581                    && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   1582                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   1583                     continue;
   1584                 }
   1585                 tag = parser.getName();
   1586                 if ("admin".equals(tag)) {
   1587                     String name = parser.getAttributeValue(null, "name");
   1588                     try {
   1589                         DeviceAdminInfo dai = findAdmin(
   1590                                 ComponentName.unflattenFromString(name), userHandle);
   1591                         if (DBG && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
   1592                                 != userHandle)) {
   1593                             Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
   1594                                     + dai.getActivityInfo().applicationInfo.uid + " for user "
   1595                                     + userHandle);
   1596                         }
   1597                         if (dai != null) {
   1598                             ActiveAdmin ap = new ActiveAdmin(dai);
   1599                             ap.readFromXml(parser);
   1600                             policy.mAdminMap.put(ap.info.getComponent(), ap);
   1601                         }
   1602                     } catch (RuntimeException e) {
   1603                         Slog.w(LOG_TAG, "Failed loading admin " + name, e);
   1604                     }
   1605                 } else if ("failed-password-attempts".equals(tag)) {
   1606                     policy.mFailedPasswordAttempts = Integer.parseInt(
   1607                             parser.getAttributeValue(null, "value"));
   1608                 } else if ("password-owner".equals(tag)) {
   1609                     policy.mPasswordOwner = Integer.parseInt(
   1610                             parser.getAttributeValue(null, "value"));
   1611                 } else if ("active-password".equals(tag)) {
   1612                     policy.mActivePasswordQuality = Integer.parseInt(
   1613                             parser.getAttributeValue(null, "quality"));
   1614                     policy.mActivePasswordLength = Integer.parseInt(
   1615                             parser.getAttributeValue(null, "length"));
   1616                     policy.mActivePasswordUpperCase = Integer.parseInt(
   1617                             parser.getAttributeValue(null, "uppercase"));
   1618                     policy.mActivePasswordLowerCase = Integer.parseInt(
   1619                             parser.getAttributeValue(null, "lowercase"));
   1620                     policy.mActivePasswordLetters = Integer.parseInt(
   1621                             parser.getAttributeValue(null, "letters"));
   1622                     policy.mActivePasswordNumeric = Integer.parseInt(
   1623                             parser.getAttributeValue(null, "numeric"));
   1624                     policy.mActivePasswordSymbols = Integer.parseInt(
   1625                             parser.getAttributeValue(null, "symbols"));
   1626                     policy.mActivePasswordNonLetter = Integer.parseInt(
   1627                             parser.getAttributeValue(null, "nonletter"));
   1628                 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
   1629                     policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
   1630                 } else if (TAG_STATUS_BAR.equals(tag)) {
   1631                     policy.mStatusBarDisabled = Boolean.parseBoolean(
   1632                             parser.getAttributeValue(null, ATTR_DISABLED));
   1633                 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
   1634                     policy.doNotAskCredentialsOnBoot = true;
   1635                 } else {
   1636                     Slog.w(LOG_TAG, "Unknown tag: " + tag);
   1637                     XmlUtils.skipCurrentTag(parser);
   1638                 }
   1639             }
   1640         } catch (NullPointerException e) {
   1641             Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
   1642         } catch (NumberFormatException e) {
   1643             Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
   1644         } catch (XmlPullParserException e) {
   1645             Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
   1646         } catch (FileNotFoundException e) {
   1647             // Don't be noisy, this is normal if we haven't defined any policies.
   1648         } catch (IOException e) {
   1649             Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
   1650         } catch (IndexOutOfBoundsException e) {
   1651             Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
   1652         }
   1653         try {
   1654             if (stream != null) {
   1655                 stream.close();
   1656             }
   1657         } catch (IOException e) {
   1658             // Ignore
   1659         }
   1660 
   1661         // Generate a list of admins from the admin map
   1662         policy.mAdminList.addAll(policy.mAdminMap.values());
   1663 
   1664         // Validate that what we stored for the password quality matches
   1665         // sufficiently what is currently set.  Note that this is only
   1666         // a sanity check in case the two get out of sync; this should
   1667         // never normally happen.
   1668         final long identity = Binder.clearCallingIdentity();
   1669         try {
   1670             LockPatternUtils utils = new LockPatternUtils(mContext);
   1671             if (utils.getActivePasswordQuality(userHandle) < policy.mActivePasswordQuality) {
   1672                 Slog.w(LOG_TAG, "Active password quality 0x"
   1673                         + Integer.toHexString(policy.mActivePasswordQuality)
   1674                         + " does not match actual quality 0x"
   1675                         + Integer.toHexString(utils.getActivePasswordQuality(userHandle)));
   1676                 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
   1677                 policy.mActivePasswordLength = 0;
   1678                 policy.mActivePasswordUpperCase = 0;
   1679                 policy.mActivePasswordLowerCase = 0;
   1680                 policy.mActivePasswordLetters = 0;
   1681                 policy.mActivePasswordNumeric = 0;
   1682                 policy.mActivePasswordSymbols = 0;
   1683                 policy.mActivePasswordNonLetter = 0;
   1684             }
   1685         } finally {
   1686             Binder.restoreCallingIdentity(identity);
   1687         }
   1688 
   1689         validatePasswordOwnerLocked(policy);
   1690         syncDeviceCapabilitiesLocked(policy);
   1691         updateMaximumTimeToLockLocked(policy);
   1692         addDeviceInitializerToLockTaskPackagesLocked(userHandle);
   1693         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
   1694         if (policy.mStatusBarDisabled) {
   1695             setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
   1696         }
   1697     }
   1698 
   1699     private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
   1700         IActivityManager am = ActivityManagerNative.getDefault();
   1701         long ident = Binder.clearCallingIdentity();
   1702         try {
   1703             am.updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
   1704         } catch (RemoteException e) {
   1705             // Not gonna happen.
   1706         } finally {
   1707             Binder.restoreCallingIdentity(ident);
   1708         }
   1709     }
   1710 
   1711     private void updateDeviceOwnerLocked() {
   1712         IActivityManager am = ActivityManagerNative.getDefault();
   1713         long ident = Binder.clearCallingIdentity();
   1714         try {
   1715             am.updateDeviceOwner(getDeviceOwner());
   1716         } catch (RemoteException e) {
   1717             // Not gonna happen.
   1718         } finally {
   1719             Binder.restoreCallingIdentity(ident);
   1720         }
   1721     }
   1722 
   1723     static void validateQualityConstant(int quality) {
   1724         switch (quality) {
   1725             case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
   1726             case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
   1727             case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
   1728             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
   1729             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
   1730             case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
   1731             case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
   1732             case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
   1733                 return;
   1734         }
   1735         throw new IllegalArgumentException("Invalid quality constant: 0x"
   1736                 + Integer.toHexString(quality));
   1737     }
   1738 
   1739     void validatePasswordOwnerLocked(DevicePolicyData policy) {
   1740         if (policy.mPasswordOwner >= 0) {
   1741             boolean haveOwner = false;
   1742             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
   1743                 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
   1744                     haveOwner = true;
   1745                     break;
   1746                 }
   1747             }
   1748             if (!haveOwner) {
   1749                 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
   1750                         + " no longer active; disabling");
   1751                 policy.mPasswordOwner = -1;
   1752             }
   1753         }
   1754     }
   1755 
   1756     /**
   1757      * Pushes down policy information to the system for any policies related to general device
   1758      * capabilities that need to be enforced by lower level services (e.g. Camera services).
   1759      */
   1760     void syncDeviceCapabilitiesLocked(DevicePolicyData policy) {
   1761         // Ensure the status of the camera is synced down to the system. Interested native services
   1762         // should monitor this value and act accordingly.
   1763         String cameraPropertyForUser = SYSTEM_PROP_DISABLE_CAMERA_PREFIX + policy.mUserHandle;
   1764         boolean systemState = SystemProperties.getBoolean(cameraPropertyForUser, false);
   1765         boolean cameraDisabled = getCameraDisabled(null, policy.mUserHandle);
   1766         if (cameraDisabled != systemState) {
   1767             long token = Binder.clearCallingIdentity();
   1768             try {
   1769                 String value = cameraDisabled ? "1" : "0";
   1770                 if (DBG) Slog.v(LOG_TAG, "Change in camera state ["
   1771                         + cameraPropertyForUser + "] = " + value);
   1772                 SystemProperties.set(cameraPropertyForUser, value);
   1773             } finally {
   1774                 Binder.restoreCallingIdentity(token);
   1775             }
   1776         }
   1777     }
   1778 
   1779     public void systemReady() {
   1780         if (!mHasFeature) {
   1781             return;
   1782         }
   1783         getUserData(UserHandle.USER_OWNER);
   1784         loadDeviceOwner();
   1785         cleanUpOldUsers();
   1786         // Register an observer for watching for user setup complete.
   1787         new SetupContentObserver(mHandler).register(mContext.getContentResolver());
   1788         // Initialize the user setup state, to handle the upgrade case.
   1789         updateUserSetupComplete();
   1790 
   1791         // Update the screen capture disabled cache in the window manager
   1792         List<UserInfo> users = mUserManager.getUsers(true);
   1793         final int N = users.size();
   1794         for (int i = 0; i < N; i++) {
   1795             int userHandle = users.get(i).id;
   1796             updateScreenCaptureDisabledInWindowManager(userHandle,
   1797                     getScreenCaptureDisabled(null, userHandle));
   1798         }
   1799     }
   1800 
   1801     private void cleanUpOldUsers() {
   1802         // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
   1803         // before reboot
   1804         Set<Integer> usersWithProfileOwners;
   1805         Set<Integer> usersWithData;
   1806         synchronized(this) {
   1807             usersWithProfileOwners = mDeviceOwner != null
   1808                     ? mDeviceOwner.getProfileOwnerKeys() : new HashSet<Integer>();
   1809             usersWithData = new HashSet<Integer>();
   1810             for (int i = 0; i < mUserData.size(); i++) {
   1811                 usersWithData.add(mUserData.keyAt(i));
   1812             }
   1813         }
   1814         List<UserInfo> allUsers = mUserManager.getUsers();
   1815 
   1816         Set<Integer> deletedUsers = new HashSet<Integer>();
   1817         deletedUsers.addAll(usersWithProfileOwners);
   1818         deletedUsers.addAll(usersWithData);
   1819         for (UserInfo userInfo : allUsers) {
   1820             deletedUsers.remove(userInfo.id);
   1821         }
   1822         for (Integer userId : deletedUsers) {
   1823             removeUserData(userId);
   1824         }
   1825     }
   1826 
   1827     private void handlePasswordExpirationNotification(int userHandle) {
   1828         synchronized (this) {
   1829             final long now = System.currentTimeMillis();
   1830 
   1831             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   1832             for (UserInfo ui : profiles) {
   1833                 int profileUserHandle = ui.id;
   1834                 final DevicePolicyData policy = getUserData(profileUserHandle);
   1835                 final int count = policy.mAdminList.size();
   1836                 if (count > 0) {
   1837                     for (int i = 0; i < count; i++) {
   1838                         final ActiveAdmin admin = policy.mAdminList.get(i);
   1839                         if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
   1840                                 && admin.passwordExpirationTimeout > 0L
   1841                                 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
   1842                                 && admin.passwordExpirationDate > 0L) {
   1843                             sendAdminCommandLocked(admin,
   1844                                     DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
   1845                         }
   1846                     }
   1847                 }
   1848             }
   1849             setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
   1850         }
   1851     }
   1852 
   1853     private class MonitoringCertNotificationTask extends AsyncTask<Intent, Void, Void> {
   1854         @Override
   1855         protected Void doInBackground(Intent... params) {
   1856             int userHandle = params[0].getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
   1857 
   1858             if (userHandle == UserHandle.USER_ALL) {
   1859                 for (UserInfo userInfo : mUserManager.getUsers()) {
   1860                     manageNotification(userInfo.getUserHandle());
   1861                 }
   1862             } else {
   1863                 manageNotification(new UserHandle(userHandle));
   1864             }
   1865             return null;
   1866         }
   1867 
   1868         private void manageNotification(UserHandle userHandle) {
   1869             if (!mUserManager.isUserRunning(userHandle)) {
   1870                 return;
   1871             }
   1872 
   1873             // Call out to KeyChain to check for user-added CAs
   1874             boolean hasCert = false;
   1875             try {
   1876                 KeyChainConnection kcs = KeyChain.bindAsUser(mContext, userHandle);
   1877                 try {
   1878                     if (!kcs.getService().getUserCaAliases().getList().isEmpty()) {
   1879                         hasCert = true;
   1880                     }
   1881                 } catch (RemoteException e) {
   1882                     Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
   1883                 } finally {
   1884                     kcs.close();
   1885                 }
   1886             } catch (InterruptedException e) {
   1887                 Thread.currentThread().interrupt();
   1888             } catch (RuntimeException e) {
   1889                 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
   1890             }
   1891             if (!hasCert) {
   1892                 getNotificationManager().cancelAsUser(
   1893                         null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
   1894                 return;
   1895             }
   1896 
   1897             // Build and show a warning notification
   1898             int smallIconId;
   1899             String contentText;
   1900             final String ownerName = getDeviceOwnerName();
   1901             if (isManagedProfile(userHandle.getIdentifier())) {
   1902                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_administrator);
   1903                 smallIconId = R.drawable.stat_sys_certificate_info;
   1904             } else if (ownerName != null) {
   1905                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, ownerName);
   1906                 smallIconId = R.drawable.stat_sys_certificate_info;
   1907             } else {
   1908                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
   1909                 smallIconId = android.R.drawable.stat_sys_warning;
   1910             }
   1911 
   1912             Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
   1913             dialogIntent.setFlags(
   1914                     Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
   1915             dialogIntent.setPackage("com.android.settings");
   1916             PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
   1917                     dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, userHandle);
   1918 
   1919             final Context userContext;
   1920             try {
   1921                 userContext = mContext.createPackageContextAsUser("android", 0, userHandle);
   1922             } catch (PackageManager.NameNotFoundException e) {
   1923                 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
   1924                 return;
   1925             }
   1926             final Notification noti = new Notification.Builder(userContext)
   1927                 .setSmallIcon(smallIconId)
   1928                 .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning))
   1929                 .setContentText(contentText)
   1930                 .setContentIntent(notifyIntent)
   1931                 .setPriority(Notification.PRIORITY_HIGH)
   1932                 .setShowWhen(false)
   1933                 .setColor(mContext.getColor(
   1934                         com.android.internal.R.color.system_notification_accent_color))
   1935                 .build();
   1936 
   1937             getNotificationManager().notifyAsUser(
   1938                     null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
   1939         }
   1940     }
   1941 
   1942     /**
   1943      * @param adminReceiver The admin to add
   1944      * @param refreshing true = update an active admin, no error
   1945      */
   1946     @Override
   1947     public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
   1948         if (!mHasFeature) {
   1949             return;
   1950         }
   1951         setActiveAdmin(adminReceiver, refreshing, userHandle, null);
   1952     }
   1953 
   1954     private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
   1955             Bundle onEnableData) {
   1956         mContext.enforceCallingOrSelfPermission(
   1957                 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
   1958         enforceCrossUserPermission(userHandle);
   1959 
   1960         DevicePolicyData policy = getUserData(userHandle);
   1961         DeviceAdminInfo info = findAdmin(adminReceiver, userHandle);
   1962         if (info == null) {
   1963             throw new IllegalArgumentException("Bad admin: " + adminReceiver);
   1964         }
   1965         synchronized (this) {
   1966             long ident = Binder.clearCallingIdentity();
   1967             try {
   1968                 if (!refreshing
   1969                         && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
   1970                     throw new IllegalArgumentException("Admin is already added");
   1971                 }
   1972                 ActiveAdmin newAdmin = new ActiveAdmin(info);
   1973                 policy.mAdminMap.put(adminReceiver, newAdmin);
   1974                 int replaceIndex = -1;
   1975                 final int N = policy.mAdminList.size();
   1976                 for (int i=0; i < N; i++) {
   1977                     ActiveAdmin oldAdmin = policy.mAdminList.get(i);
   1978                     if (oldAdmin.info.getComponent().equals(adminReceiver)) {
   1979                         replaceIndex = i;
   1980                         break;
   1981                     }
   1982                 }
   1983                 if (replaceIndex == -1) {
   1984                     policy.mAdminList.add(newAdmin);
   1985                     enableIfNecessary(info.getPackageName(), userHandle);
   1986                 } else {
   1987                     policy.mAdminList.set(replaceIndex, newAdmin);
   1988                 }
   1989                 saveSettingsLocked(userHandle);
   1990                 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
   1991                         onEnableData, null);
   1992             } finally {
   1993                 Binder.restoreCallingIdentity(ident);
   1994             }
   1995         }
   1996     }
   1997 
   1998     @Override
   1999     public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
   2000         if (!mHasFeature) {
   2001             return false;
   2002         }
   2003         enforceCrossUserPermission(userHandle);
   2004         synchronized (this) {
   2005             return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
   2006         }
   2007     }
   2008 
   2009     @Override
   2010     public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
   2011         if (!mHasFeature) {
   2012             return false;
   2013         }
   2014         enforceCrossUserPermission(userHandle);
   2015         synchronized (this) {
   2016             DevicePolicyData policyData = getUserData(userHandle);
   2017             return policyData.mRemovingAdmins.contains(adminReceiver);
   2018         }
   2019     }
   2020 
   2021     @Override
   2022     public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
   2023         if (!mHasFeature) {
   2024             return false;
   2025         }
   2026         enforceCrossUserPermission(userHandle);
   2027         synchronized (this) {
   2028             ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
   2029             if (administrator == null) {
   2030                 throw new SecurityException("No active admin " + adminReceiver);
   2031             }
   2032             return administrator.info.usesPolicy(policyId);
   2033         }
   2034     }
   2035 
   2036     @Override
   2037     @SuppressWarnings("unchecked")
   2038     public List<ComponentName> getActiveAdmins(int userHandle) {
   2039         if (!mHasFeature) {
   2040             return Collections.EMPTY_LIST;
   2041         }
   2042 
   2043         enforceCrossUserPermission(userHandle);
   2044         synchronized (this) {
   2045             DevicePolicyData policy = getUserData(userHandle);
   2046             final int N = policy.mAdminList.size();
   2047             if (N <= 0) {
   2048                 return null;
   2049             }
   2050             ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
   2051             for (int i=0; i<N; i++) {
   2052                 res.add(policy.mAdminList.get(i).info.getComponent());
   2053             }
   2054             return res;
   2055         }
   2056     }
   2057 
   2058     @Override
   2059     public boolean packageHasActiveAdmins(String packageName, int userHandle) {
   2060         if (!mHasFeature) {
   2061             return false;
   2062         }
   2063         enforceCrossUserPermission(userHandle);
   2064         synchronized (this) {
   2065             DevicePolicyData policy = getUserData(userHandle);
   2066             final int N = policy.mAdminList.size();
   2067             for (int i=0; i<N; i++) {
   2068                 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
   2069                     return true;
   2070                 }
   2071             }
   2072             return false;
   2073         }
   2074     }
   2075 
   2076     @Override
   2077     public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
   2078         if (!mHasFeature) {
   2079             return;
   2080         }
   2081         enforceCrossUserPermission(userHandle);
   2082         synchronized (this) {
   2083             ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
   2084             if (admin == null) {
   2085                 return;
   2086             }
   2087             if (admin.getUid() != Binder.getCallingUid()) {
   2088                 // Active device owners must remain active admins.
   2089                 if (isDeviceOwner(adminReceiver.getPackageName())) {
   2090                     return;
   2091                 }
   2092                 mContext.enforceCallingOrSelfPermission(
   2093                         android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
   2094             }
   2095             long ident = Binder.clearCallingIdentity();
   2096             try {
   2097                 removeActiveAdminLocked(adminReceiver, userHandle);
   2098             } finally {
   2099                 Binder.restoreCallingIdentity(ident);
   2100             }
   2101         }
   2102     }
   2103 
   2104     @Override
   2105     public void setPasswordQuality(ComponentName who, int quality) {
   2106         if (!mHasFeature) {
   2107             return;
   2108         }
   2109         Preconditions.checkNotNull(who, "ComponentName is null");
   2110         final int userHandle = UserHandle.getCallingUserId();
   2111         validateQualityConstant(quality);
   2112 
   2113         synchronized (this) {
   2114             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   2115                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   2116             if (ap.passwordQuality != quality) {
   2117                 ap.passwordQuality = quality;
   2118                 saveSettingsLocked(userHandle);
   2119             }
   2120         }
   2121     }
   2122 
   2123     @Override
   2124     public int getPasswordQuality(ComponentName who, int userHandle) {
   2125         if (!mHasFeature) {
   2126             return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
   2127         }
   2128         enforceCrossUserPermission(userHandle);
   2129         synchronized (this) {
   2130             int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
   2131 
   2132             if (who != null) {
   2133                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   2134                 return admin != null ? admin.passwordQuality : mode;
   2135             }
   2136 
   2137             // Return strictest policy for this user and profiles that are visible from this user.
   2138             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   2139             for (UserInfo userInfo : profiles) {
   2140                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2141                 final int N = policy.mAdminList.size();
   2142                 for (int i=0; i<N; i++) {
   2143                     ActiveAdmin admin = policy.mAdminList.get(i);
   2144                     if (mode < admin.passwordQuality) {
   2145                         mode = admin.passwordQuality;
   2146                     }
   2147                 }
   2148             }
   2149             return mode;
   2150         }
   2151     }
   2152 
   2153     @Override
   2154     public void setPasswordMinimumLength(ComponentName who, int length) {
   2155         if (!mHasFeature) {
   2156             return;
   2157         }
   2158         Preconditions.checkNotNull(who, "ComponentName is null");
   2159         final int userHandle = UserHandle.getCallingUserId();
   2160         synchronized (this) {
   2161             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   2162                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   2163             if (ap.minimumPasswordLength != length) {
   2164                 ap.minimumPasswordLength = length;
   2165                 saveSettingsLocked(userHandle);
   2166             }
   2167         }
   2168     }
   2169 
   2170     @Override
   2171     public int getPasswordMinimumLength(ComponentName who, int userHandle) {
   2172         if (!mHasFeature) {
   2173             return 0;
   2174         }
   2175         enforceCrossUserPermission(userHandle);
   2176         synchronized (this) {
   2177             int length = 0;
   2178 
   2179             if (who != null) {
   2180                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   2181                 return admin != null ? admin.minimumPasswordLength : length;
   2182             }
   2183 
   2184             // Return strictest policy for this user and profiles that are visible from this user.
   2185             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   2186             for (UserInfo userInfo : profiles) {
   2187                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2188                 final int N = policy.mAdminList.size();
   2189                 for (int i=0; i<N; i++) {
   2190                     ActiveAdmin admin = policy.mAdminList.get(i);
   2191                     if (length < admin.minimumPasswordLength) {
   2192                         length = admin.minimumPasswordLength;
   2193                     }
   2194                 }
   2195             }
   2196             return length;
   2197         }
   2198     }
   2199 
   2200     @Override
   2201     public void setPasswordHistoryLength(ComponentName who, int length) {
   2202         if (!mHasFeature) {
   2203             return;
   2204         }
   2205         Preconditions.checkNotNull(who, "ComponentName is null");
   2206         final int userHandle = UserHandle.getCallingUserId();
   2207         synchronized (this) {
   2208             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   2209                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   2210             if (ap.passwordHistoryLength != length) {
   2211                 ap.passwordHistoryLength = length;
   2212                 saveSettingsLocked(userHandle);
   2213             }
   2214         }
   2215     }
   2216 
   2217     @Override
   2218     public int getPasswordHistoryLength(ComponentName who, int userHandle) {
   2219         if (!mHasFeature) {
   2220             return 0;
   2221         }
   2222         enforceCrossUserPermission(userHandle);
   2223         synchronized (this) {
   2224             int length = 0;
   2225 
   2226             if (who != null) {
   2227                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   2228                 return admin != null ? admin.passwordHistoryLength : length;
   2229             }
   2230 
   2231             // Return strictest policy for this user and profiles that are visible from this user.
   2232             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   2233             for (UserInfo userInfo : profiles) {
   2234                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2235                 final int N = policy.mAdminList.size();
   2236                 for (int i = 0; i < N; i++) {
   2237                     ActiveAdmin admin = policy.mAdminList.get(i);
   2238                     if (length < admin.passwordHistoryLength) {
   2239                         length = admin.passwordHistoryLength;
   2240                     }
   2241                 }
   2242             }
   2243             return length;
   2244         }
   2245     }
   2246 
   2247     @Override
   2248     public void setPasswordExpirationTimeout(ComponentName who, long timeout) {
   2249         if (!mHasFeature) {
   2250             return;
   2251         }
   2252         Preconditions.checkNotNull(who, "ComponentName is null");
   2253         Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
   2254         final int userHandle = UserHandle.getCallingUserId();
   2255         synchronized (this) {
   2256             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   2257                     DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
   2258             // Calling this API automatically bumps the expiration date
   2259             final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
   2260             ap.passwordExpirationDate = expiration;
   2261             ap.passwordExpirationTimeout = timeout;
   2262             if (timeout > 0L) {
   2263                 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
   2264                         + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
   2265                         .format(new Date(expiration)));
   2266             }
   2267             saveSettingsLocked(userHandle);
   2268             // in case this is the first one
   2269             setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
   2270         }
   2271     }
   2272 
   2273     /**
   2274      * Return a single admin's expiration cycle time, or the min of all cycle times.
   2275      * Returns 0 if not configured.
   2276      */
   2277     @Override
   2278     public long getPasswordExpirationTimeout(ComponentName who, int userHandle) {
   2279         if (!mHasFeature) {
   2280             return 0L;
   2281         }
   2282         enforceCrossUserPermission(userHandle);
   2283         synchronized (this) {
   2284             long timeout = 0L;
   2285 
   2286             if (who != null) {
   2287                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   2288                 return admin != null ? admin.passwordExpirationTimeout : timeout;
   2289             }
   2290 
   2291             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   2292             for (UserInfo userInfo : profiles) {
   2293                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2294                 final int N = policy.mAdminList.size();
   2295                 for (int i = 0; i < N; i++) {
   2296                     ActiveAdmin admin = policy.mAdminList.get(i);
   2297                     if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
   2298                             && timeout > admin.passwordExpirationTimeout)) {
   2299                         timeout = admin.passwordExpirationTimeout;
   2300                     }
   2301                 }
   2302             }
   2303             return timeout;
   2304         }
   2305     }
   2306 
   2307     @Override
   2308     public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
   2309         final int userId = UserHandle.getCallingUserId();
   2310         List<String> changedProviders = null;
   2311 
   2312         synchronized (this) {
   2313             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
   2314                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   2315             if (activeAdmin.crossProfileWidgetProviders == null) {
   2316                 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
   2317             }
   2318             List<String> providers = activeAdmin.crossProfileWidgetProviders;
   2319             if (!providers.contains(packageName)) {
   2320                 providers.add(packageName);
   2321                 changedProviders = new ArrayList<>(providers);
   2322                 saveSettingsLocked(userId);
   2323             }
   2324         }
   2325 
   2326         if (changedProviders != null) {
   2327             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
   2328             return true;
   2329         }
   2330 
   2331         return false;
   2332     }
   2333 
   2334     @Override
   2335     public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
   2336         final int userId = UserHandle.getCallingUserId();
   2337         List<String> changedProviders = null;
   2338 
   2339         synchronized (this) {
   2340             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
   2341                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   2342             if (activeAdmin.crossProfileWidgetProviders == null) {
   2343                 return false;
   2344             }
   2345             List<String> providers = activeAdmin.crossProfileWidgetProviders;
   2346             if (providers.remove(packageName)) {
   2347                 changedProviders = new ArrayList<>(providers);
   2348                 saveSettingsLocked(userId);
   2349             }
   2350         }
   2351 
   2352         if (changedProviders != null) {
   2353             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
   2354             return true;
   2355         }
   2356 
   2357         return false;
   2358     }
   2359 
   2360     @Override
   2361     public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
   2362         synchronized (this) {
   2363             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
   2364                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   2365             if (activeAdmin.crossProfileWidgetProviders == null
   2366                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
   2367                 return null;
   2368             }
   2369             if (Binder.getCallingUid() == Process.myUid()) {
   2370                 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
   2371             } else {
   2372                 return activeAdmin.crossProfileWidgetProviders;
   2373             }
   2374         }
   2375     }
   2376 
   2377     /**
   2378      * Return a single admin's expiration date/time, or the min (soonest) for all admins.
   2379      * Returns 0 if not configured.
   2380      */
   2381     private long getPasswordExpirationLocked(ComponentName who, int userHandle) {
   2382         long timeout = 0L;
   2383 
   2384         if (who != null) {
   2385             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   2386             return admin != null ? admin.passwordExpirationDate : timeout;
   2387         }
   2388 
   2389         List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   2390         for (UserInfo userInfo : profiles) {
   2391             DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2392             final int N = policy.mAdminList.size();
   2393             for (int i = 0; i < N; i++) {
   2394                 ActiveAdmin admin = policy.mAdminList.get(i);
   2395                 if (timeout == 0L || (admin.passwordExpirationDate != 0
   2396                         && timeout > admin.passwordExpirationDate)) {
   2397                     timeout = admin.passwordExpirationDate;
   2398                 }
   2399             }
   2400         }
   2401         return timeout;
   2402     }
   2403 
   2404     @Override
   2405     public long getPasswordExpiration(ComponentName who, int userHandle) {
   2406         if (!mHasFeature) {
   2407             return 0L;
   2408         }
   2409         enforceCrossUserPermission(userHandle);
   2410         synchronized (this) {
   2411             return getPasswordExpirationLocked(who, userHandle);
   2412         }
   2413     }
   2414 
   2415     @Override
   2416     public void setPasswordMinimumUpperCase(ComponentName who, int length) {
   2417         if (!mHasFeature) {
   2418             return;
   2419         }
   2420         Preconditions.checkNotNull(who, "ComponentName is null");
   2421         final int userHandle = UserHandle.getCallingUserId();
   2422         synchronized (this) {
   2423             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   2424                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   2425             if (ap.minimumPasswordUpperCase != length) {
   2426                 ap.minimumPasswordUpperCase = length;
   2427                 saveSettingsLocked(userHandle);
   2428             }
   2429         }
   2430     }
   2431 
   2432     @Override
   2433     public int getPasswordMinimumUpperCase(ComponentName who, int userHandle) {
   2434         if (!mHasFeature) {
   2435             return 0;
   2436         }
   2437         enforceCrossUserPermission(userHandle);
   2438         synchronized (this) {
   2439             int length = 0;
   2440 
   2441             if (who != null) {
   2442                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   2443                 return admin != null ? admin.minimumPasswordUpperCase : length;
   2444             }
   2445 
   2446             // Return strictest policy for this user and profiles that are visible from this user.
   2447             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   2448             for (UserInfo userInfo : profiles) {
   2449                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2450                 final int N = policy.mAdminList.size();
   2451                 for (int i=0; i<N; i++) {
   2452                     ActiveAdmin admin = policy.mAdminList.get(i);
   2453                     if (length < admin.minimumPasswordUpperCase) {
   2454                         length = admin.minimumPasswordUpperCase;
   2455                     }
   2456                 }
   2457             }
   2458             return length;
   2459         }
   2460     }
   2461 
   2462     @Override
   2463     public void setPasswordMinimumLowerCase(ComponentName who, int length) {
   2464         Preconditions.checkNotNull(who, "ComponentName is null");
   2465         final int userHandle = UserHandle.getCallingUserId();
   2466         synchronized (this) {
   2467             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   2468                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   2469             if (ap.minimumPasswordLowerCase != length) {
   2470                 ap.minimumPasswordLowerCase = length;
   2471                 saveSettingsLocked(userHandle);
   2472             }
   2473         }
   2474     }
   2475 
   2476     @Override
   2477     public int getPasswordMinimumLowerCase(ComponentName who, int userHandle) {
   2478         if (!mHasFeature) {
   2479             return 0;
   2480         }
   2481         enforceCrossUserPermission(userHandle);
   2482         synchronized (this) {
   2483             int length = 0;
   2484 
   2485             if (who != null) {
   2486                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   2487                 return admin != null ? admin.minimumPasswordLowerCase : length;
   2488             }
   2489 
   2490             // Return strictest policy for this user and profiles that are visible from this user.
   2491             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   2492             for (UserInfo userInfo : profiles) {
   2493                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2494                 final int N = policy.mAdminList.size();
   2495                 for (int i=0; i<N; i++) {
   2496                     ActiveAdmin admin = policy.mAdminList.get(i);
   2497                     if (length < admin.minimumPasswordLowerCase) {
   2498                         length = admin.minimumPasswordLowerCase;
   2499                     }
   2500                 }
   2501             }
   2502             return length;
   2503         }
   2504     }
   2505 
   2506     @Override
   2507     public void setPasswordMinimumLetters(ComponentName who, int length) {
   2508         if (!mHasFeature) {
   2509             return;
   2510         }
   2511         Preconditions.checkNotNull(who, "ComponentName is null");
   2512         final int userHandle = UserHandle.getCallingUserId();
   2513         synchronized (this) {
   2514             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   2515                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   2516             if (ap.minimumPasswordLetters != length) {
   2517                 ap.minimumPasswordLetters = length;
   2518                 saveSettingsLocked(userHandle);
   2519             }
   2520         }
   2521     }
   2522 
   2523     @Override
   2524     public int getPasswordMinimumLetters(ComponentName who, int userHandle) {
   2525         if (!mHasFeature) {
   2526             return 0;
   2527         }
   2528         enforceCrossUserPermission(userHandle);
   2529         synchronized (this) {
   2530             int length = 0;
   2531 
   2532             if (who != null) {
   2533                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   2534                 return admin != null ? admin.minimumPasswordLetters : length;
   2535             }
   2536 
   2537             // Return strictest policy for this user and profiles that are visible from this user.
   2538             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   2539             for (UserInfo userInfo : profiles) {
   2540                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2541                 final int N = policy.mAdminList.size();
   2542                 for (int i=0; i<N; i++) {
   2543                     ActiveAdmin admin = policy.mAdminList.get(i);
   2544                     if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
   2545                         continue;
   2546                     }
   2547                     if (length < admin.minimumPasswordLetters) {
   2548                         length = admin.minimumPasswordLetters;
   2549                     }
   2550                 }
   2551             }
   2552             return length;
   2553         }
   2554     }
   2555 
   2556     @Override
   2557     public void setPasswordMinimumNumeric(ComponentName who, int length) {
   2558         if (!mHasFeature) {
   2559             return;
   2560         }
   2561         Preconditions.checkNotNull(who, "ComponentName is null");
   2562         final int userHandle = UserHandle.getCallingUserId();
   2563         synchronized (this) {
   2564             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   2565                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   2566             if (ap.minimumPasswordNumeric != length) {
   2567                 ap.minimumPasswordNumeric = length;
   2568                 saveSettingsLocked(userHandle);
   2569             }
   2570         }
   2571     }
   2572 
   2573     @Override
   2574     public int getPasswordMinimumNumeric(ComponentName who, int userHandle) {
   2575         if (!mHasFeature) {
   2576             return 0;
   2577         }
   2578         enforceCrossUserPermission(userHandle);
   2579         synchronized (this) {
   2580             int length = 0;
   2581 
   2582             if (who != null) {
   2583                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   2584                 return admin != null ? admin.minimumPasswordNumeric : length;
   2585             }
   2586 
   2587             // Return strictest policy for this user and profiles that are visible from this user.
   2588             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   2589             for (UserInfo userInfo : profiles) {
   2590                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2591                 final int N = policy.mAdminList.size();
   2592                 for (int i = 0; i < N; i++) {
   2593                     ActiveAdmin admin = policy.mAdminList.get(i);
   2594                     if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
   2595                         continue;
   2596                     }
   2597                     if (length < admin.minimumPasswordNumeric) {
   2598                         length = admin.minimumPasswordNumeric;
   2599                     }
   2600                 }
   2601             }
   2602             return length;
   2603         }
   2604     }
   2605 
   2606     @Override
   2607     public void setPasswordMinimumSymbols(ComponentName who, int length) {
   2608         if (!mHasFeature) {
   2609             return;
   2610         }
   2611         Preconditions.checkNotNull(who, "ComponentName is null");
   2612         final int userHandle = UserHandle.getCallingUserId();
   2613         synchronized (this) {
   2614             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   2615                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   2616             if (ap.minimumPasswordSymbols != length) {
   2617                 ap.minimumPasswordSymbols = length;
   2618                 saveSettingsLocked(userHandle);
   2619             }
   2620         }
   2621     }
   2622 
   2623     @Override
   2624     public int getPasswordMinimumSymbols(ComponentName who, int userHandle) {
   2625         if (!mHasFeature) {
   2626             return 0;
   2627         }
   2628         enforceCrossUserPermission(userHandle);
   2629         synchronized (this) {
   2630             int length = 0;
   2631 
   2632             if (who != null) {
   2633                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   2634                 return admin != null ? admin.minimumPasswordSymbols : length;
   2635             }
   2636 
   2637             // Return strictest policy for this user and profiles that are visible from this user.
   2638             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   2639             for (UserInfo userInfo : profiles) {
   2640                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2641                 final int N = policy.mAdminList.size();
   2642                 for (int i=0; i<N; i++) {
   2643                     ActiveAdmin admin = policy.mAdminList.get(i);
   2644                     if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
   2645                         continue;
   2646                     }
   2647                     if (length < admin.minimumPasswordSymbols) {
   2648                         length = admin.minimumPasswordSymbols;
   2649                     }
   2650                 }
   2651             }
   2652             return length;
   2653         }
   2654     }
   2655 
   2656     @Override
   2657     public void setPasswordMinimumNonLetter(ComponentName who, int length) {
   2658         if (!mHasFeature) {
   2659             return;
   2660         }
   2661         Preconditions.checkNotNull(who, "ComponentName is null");
   2662         final int userHandle = UserHandle.getCallingUserId();
   2663         synchronized (this) {
   2664             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   2665                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   2666             if (ap.minimumPasswordNonLetter != length) {
   2667                 ap.minimumPasswordNonLetter = length;
   2668                 saveSettingsLocked(userHandle);
   2669             }
   2670         }
   2671     }
   2672 
   2673     @Override
   2674     public int getPasswordMinimumNonLetter(ComponentName who, int userHandle) {
   2675         if (!mHasFeature) {
   2676             return 0;
   2677         }
   2678         enforceCrossUserPermission(userHandle);
   2679         synchronized (this) {
   2680             int length = 0;
   2681 
   2682             if (who != null) {
   2683                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   2684                 return admin != null ? admin.minimumPasswordNonLetter : length;
   2685             }
   2686 
   2687             // Return strictest policy for this user and profiles that are visible from this user.
   2688             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   2689             for (UserInfo userInfo : profiles) {
   2690                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2691                 final int N = policy.mAdminList.size();
   2692                 for (int i=0; i<N; i++) {
   2693                     ActiveAdmin admin = policy.mAdminList.get(i);
   2694                     if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
   2695                         continue;
   2696                     }
   2697                     if (length < admin.minimumPasswordNonLetter) {
   2698                         length = admin.minimumPasswordNonLetter;
   2699                     }
   2700                 }
   2701             }
   2702             return length;
   2703         }
   2704     }
   2705 
   2706     @Override
   2707     public boolean isActivePasswordSufficient(int userHandle) {
   2708         if (!mHasFeature) {
   2709             return true;
   2710         }
   2711         enforceCrossUserPermission(userHandle);
   2712 
   2713         synchronized (this) {
   2714 
   2715             // The active password is stored in the user that runs the launcher
   2716             // If the user this is called from is part of a profile group, that is the parent
   2717             // of the group.
   2718             UserInfo parent = getProfileParent(userHandle);
   2719             int id = (parent == null) ? userHandle : parent.id;
   2720             DevicePolicyData policy = getUserDataUnchecked(id);
   2721 
   2722             // This API can only be called by an active device admin,
   2723             // so try to retrieve it to check that the caller is one.
   2724             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   2725             if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle)
   2726                     || policy.mActivePasswordLength < getPasswordMinimumLength(null, userHandle)) {
   2727                 return false;
   2728             }
   2729             if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
   2730                 return true;
   2731             }
   2732             return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(null, userHandle)
   2733                 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(null, userHandle)
   2734                 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(null, userHandle)
   2735                 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(null, userHandle)
   2736                 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(null, userHandle)
   2737                 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(null, userHandle);
   2738         }
   2739     }
   2740 
   2741     @Override
   2742     public int getCurrentFailedPasswordAttempts(int userHandle) {
   2743         synchronized (this) {
   2744             // This API can only be called by an active device admin,
   2745             // so try to retrieve it to check that the caller is one.
   2746             getActiveAdminForCallerLocked(null,
   2747                     DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
   2748 
   2749             // The active password is stored in the parent.
   2750             UserInfo parent = getProfileParent(userHandle);
   2751             int id = (parent == null) ? userHandle : parent.id;
   2752             DevicePolicyData policy = getUserDataUnchecked(id);
   2753 
   2754             return policy.mFailedPasswordAttempts;
   2755         }
   2756     }
   2757 
   2758     @Override
   2759     public void setMaximumFailedPasswordsForWipe(ComponentName who, int num) {
   2760         if (!mHasFeature) {
   2761             return;
   2762         }
   2763         Preconditions.checkNotNull(who, "ComponentName is null");
   2764         final int userHandle = UserHandle.getCallingUserId();
   2765         synchronized (this) {
   2766             // This API can only be called by an active device admin,
   2767             // so try to retrieve it to check that the caller is one.
   2768             getActiveAdminForCallerLocked(who,
   2769                     DeviceAdminInfo.USES_POLICY_WIPE_DATA);
   2770             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   2771                     DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
   2772             if (ap.maximumFailedPasswordsForWipe != num) {
   2773                 ap.maximumFailedPasswordsForWipe = num;
   2774                 saveSettingsLocked(userHandle);
   2775             }
   2776         }
   2777     }
   2778 
   2779     @Override
   2780     public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle) {
   2781         if (!mHasFeature) {
   2782             return 0;
   2783         }
   2784         enforceCrossUserPermission(userHandle);
   2785         synchronized (this) {
   2786             ActiveAdmin admin = (who != null) ? getActiveAdminUncheckedLocked(who, userHandle)
   2787                     : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
   2788             return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
   2789         }
   2790     }
   2791 
   2792     @Override
   2793     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
   2794         if (!mHasFeature) {
   2795             return UserHandle.USER_NULL;
   2796         }
   2797         enforceCrossUserPermission(userHandle);
   2798         synchronized (this) {
   2799             ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
   2800             return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
   2801         }
   2802     }
   2803 
   2804     /**
   2805      * Returns the admin with the strictest policy on maximum failed passwords for this user and all
   2806      * profiles that are visible from this user. If the policy for the primary and any other profile
   2807      * are equal, it returns the admin for the primary profile.
   2808      * Returns {@code null} if none of them have that policy set.
   2809      */
   2810     private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(int userHandle) {
   2811         int count = 0;
   2812         ActiveAdmin strictestAdmin = null;
   2813         for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
   2814             DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   2815             for (ActiveAdmin admin : policy.mAdminList) {
   2816                 if (admin.maximumFailedPasswordsForWipe ==
   2817                         ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
   2818                     continue;  // No max number of failed passwords policy set for this profile.
   2819                 }
   2820 
   2821                 // We always favor the primary profile if several profiles have the same value set.
   2822                 if (count == 0 ||
   2823                         count > admin.maximumFailedPasswordsForWipe ||
   2824                         (userInfo.isPrimary() && count >= admin.maximumFailedPasswordsForWipe)) {
   2825                     count = admin.maximumFailedPasswordsForWipe;
   2826                     strictestAdmin = admin;
   2827                 }
   2828             }
   2829         }
   2830         return strictestAdmin;
   2831     }
   2832 
   2833     @Override
   2834     public boolean resetPassword(String passwordOrNull, int flags) {
   2835         if (!mHasFeature) {
   2836             return false;
   2837         }
   2838         final int userHandle = UserHandle.getCallingUserId();
   2839         enforceNotManagedProfile(userHandle, "reset the password");
   2840 
   2841         String password = passwordOrNull != null ? passwordOrNull : "";
   2842 
   2843         int quality;
   2844         synchronized (this) {
   2845             // This api can only be called by an active device admin,
   2846             // so try to retrieve it to check that the caller is one.
   2847             getActiveAdminForCallerLocked(null,
   2848                     DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
   2849             quality = getPasswordQuality(null, userHandle);
   2850             if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
   2851                 int realQuality = LockPatternUtils.computePasswordQuality(password);
   2852                 if (realQuality < quality
   2853                         && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
   2854                     Slog.w(LOG_TAG, "resetPassword: password quality 0x"
   2855                             + Integer.toHexString(realQuality)
   2856                             + " does not meet required quality 0x"
   2857                             + Integer.toHexString(quality));
   2858                     return false;
   2859                 }
   2860                 quality = Math.max(realQuality, quality);
   2861             }
   2862             int length = getPasswordMinimumLength(null, userHandle);
   2863             if (password.length() < length) {
   2864                 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
   2865                         + " does not meet required length " + length);
   2866                 return false;
   2867             }
   2868             if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
   2869                 int letters = 0;
   2870                 int uppercase = 0;
   2871                 int lowercase = 0;
   2872                 int numbers = 0;
   2873                 int symbols = 0;
   2874                 int nonletter = 0;
   2875                 for (int i = 0; i < password.length(); i++) {
   2876                     char c = password.charAt(i);
   2877                     if (c >= 'A' && c <= 'Z') {
   2878                         letters++;
   2879                         uppercase++;
   2880                     } else if (c >= 'a' && c <= 'z') {
   2881                         letters++;
   2882                         lowercase++;
   2883                     } else if (c >= '0' && c <= '9') {
   2884                         numbers++;
   2885                         nonletter++;
   2886                     } else {
   2887                         symbols++;
   2888                         nonletter++;
   2889                     }
   2890                 }
   2891                 int neededLetters = getPasswordMinimumLetters(null, userHandle);
   2892                 if(letters < neededLetters) {
   2893                     Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
   2894                             + " does not meet required number of letters " + neededLetters);
   2895                     return false;
   2896                 }
   2897                 int neededNumbers = getPasswordMinimumNumeric(null, userHandle);
   2898                 if (numbers < neededNumbers) {
   2899                     Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
   2900                             + " does not meet required number of numerical digits "
   2901                             + neededNumbers);
   2902                     return false;
   2903                 }
   2904                 int neededLowerCase = getPasswordMinimumLowerCase(null, userHandle);
   2905                 if (lowercase < neededLowerCase) {
   2906                     Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
   2907                             + " does not meet required number of lowercase letters "
   2908                             + neededLowerCase);
   2909                     return false;
   2910                 }
   2911                 int neededUpperCase = getPasswordMinimumUpperCase(null, userHandle);
   2912                 if (uppercase < neededUpperCase) {
   2913                     Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
   2914                             + " does not meet required number of uppercase letters "
   2915                             + neededUpperCase);
   2916                     return false;
   2917                 }
   2918                 int neededSymbols = getPasswordMinimumSymbols(null, userHandle);
   2919                 if (symbols < neededSymbols) {
   2920                     Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
   2921                             + " does not meet required number of special symbols " + neededSymbols);
   2922                     return false;
   2923                 }
   2924                 int neededNonLetter = getPasswordMinimumNonLetter(null, userHandle);
   2925                 if (nonletter < neededNonLetter) {
   2926                     Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
   2927                             + " does not meet required number of non-letter characters "
   2928                             + neededNonLetter);
   2929                     return false;
   2930                 }
   2931             }
   2932         }
   2933 
   2934         int callingUid = Binder.getCallingUid();
   2935         DevicePolicyData policy = getUserData(userHandle);
   2936         if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
   2937             Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
   2938             return false;
   2939         }
   2940 
   2941         boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwnerOrInitializer(callingUid);
   2942         boolean doNotAskCredentialsOnBoot =
   2943                 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
   2944         if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
   2945             setDoNotAskCredentialsOnBoot();
   2946         }
   2947 
   2948         // Don't do this with the lock held, because it is going to call
   2949         // back in to the service.
   2950         long ident = Binder.clearCallingIdentity();
   2951         try {
   2952             LockPatternUtils utils = new LockPatternUtils(mContext);
   2953             if (!TextUtils.isEmpty(password)) {
   2954                 utils.saveLockPassword(password, null, quality, userHandle);
   2955             } else {
   2956                 utils.clearLock(userHandle);
   2957             }
   2958             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
   2959             if (requireEntry) {
   2960                 utils.requireCredentialEntry(UserHandle.USER_ALL);
   2961             }
   2962             synchronized (this) {
   2963                 int newOwner = requireEntry ? callingUid : -1;
   2964                 if (policy.mPasswordOwner != newOwner) {
   2965                     policy.mPasswordOwner = newOwner;
   2966                     saveSettingsLocked(userHandle);
   2967                 }
   2968             }
   2969         } finally {
   2970             Binder.restoreCallingIdentity(ident);
   2971         }
   2972 
   2973         return true;
   2974     }
   2975 
   2976     private void setDoNotAskCredentialsOnBoot() {
   2977         synchronized (this) {
   2978             DevicePolicyData policyData = getUserData(UserHandle.USER_OWNER);
   2979             if (!policyData.doNotAskCredentialsOnBoot) {
   2980                 policyData.doNotAskCredentialsOnBoot = true;
   2981                 saveSettingsLocked(UserHandle.USER_OWNER);
   2982             }
   2983         }
   2984     }
   2985 
   2986     @Override
   2987     public boolean getDoNotAskCredentialsOnBoot() {
   2988         mContext.enforceCallingOrSelfPermission(
   2989                 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
   2990         synchronized (this) {
   2991             DevicePolicyData policyData = getUserData(UserHandle.USER_OWNER);
   2992             return policyData.doNotAskCredentialsOnBoot;
   2993         }
   2994     }
   2995 
   2996     @Override
   2997     public void setMaximumTimeToLock(ComponentName who, long timeMs) {
   2998         if (!mHasFeature) {
   2999             return;
   3000         }
   3001         Preconditions.checkNotNull(who, "ComponentName is null");
   3002         final int userHandle = UserHandle.getCallingUserId();
   3003         synchronized (this) {
   3004             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   3005                     DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
   3006             if (ap.maximumTimeToUnlock != timeMs) {
   3007                 ap.maximumTimeToUnlock = timeMs;
   3008                 saveSettingsLocked(userHandle);
   3009                 updateMaximumTimeToLockLocked(getUserData(userHandle));
   3010             }
   3011         }
   3012     }
   3013 
   3014     void updateMaximumTimeToLockLocked(DevicePolicyData policy) {
   3015         long timeMs = getMaximumTimeToLock(null, policy.mUserHandle);
   3016         if (policy.mLastMaximumTimeToLock == timeMs) {
   3017             return;
   3018         }
   3019 
   3020         long ident = Binder.clearCallingIdentity();
   3021         try {
   3022             if (timeMs <= 0) {
   3023                 timeMs = Integer.MAX_VALUE;
   3024             } else {
   3025                 // Make sure KEEP_SCREEN_ON is disabled, since that
   3026                 // would allow bypassing of the maximum time to lock.
   3027                 Settings.Global.putInt(mContext.getContentResolver(),
   3028                         Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
   3029             }
   3030 
   3031             policy.mLastMaximumTimeToLock = timeMs;
   3032             mPowerManagerInternal.setMaximumScreenOffTimeoutFromDeviceAdmin((int)timeMs);
   3033         } finally {
   3034             Binder.restoreCallingIdentity(ident);
   3035         }
   3036     }
   3037 
   3038     @Override
   3039     public long getMaximumTimeToLock(ComponentName who, int userHandle) {
   3040         if (!mHasFeature) {
   3041             return 0;
   3042         }
   3043         enforceCrossUserPermission(userHandle);
   3044         synchronized (this) {
   3045             long time = 0;
   3046 
   3047             if (who != null) {
   3048                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   3049                 return admin != null ? admin.maximumTimeToUnlock : time;
   3050             }
   3051 
   3052             // Return strictest policy for this user and profiles that are visible from this user.
   3053             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   3054             for (UserInfo userInfo : profiles) {
   3055                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   3056                 final int N = policy.mAdminList.size();
   3057                 for (int i=0; i<N; i++) {
   3058                     ActiveAdmin admin = policy.mAdminList.get(i);
   3059                     if (time == 0) {
   3060                         time = admin.maximumTimeToUnlock;
   3061                     } else if (admin.maximumTimeToUnlock != 0
   3062                             && time > admin.maximumTimeToUnlock) {
   3063                         time = admin.maximumTimeToUnlock;
   3064                     }
   3065                 }
   3066             }
   3067             return time;
   3068         }
   3069     }
   3070 
   3071     @Override
   3072     public void lockNow() {
   3073         if (!mHasFeature) {
   3074             return;
   3075         }
   3076         synchronized (this) {
   3077             // This API can only be called by an active device admin,
   3078             // so try to retrieve it to check that the caller is one.
   3079             getActiveAdminForCallerLocked(null,
   3080                     DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
   3081             lockNowUnchecked();
   3082         }
   3083     }
   3084 
   3085     private void lockNowUnchecked() {
   3086         long ident = Binder.clearCallingIdentity();
   3087         try {
   3088             // Power off the display
   3089             mPowerManager.goToSleep(SystemClock.uptimeMillis(),
   3090                     PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
   3091             // Ensure the device is locked
   3092             new LockPatternUtils(mContext).requireCredentialEntry(UserHandle.USER_ALL);
   3093             getWindowManager().lockNow(null);
   3094         } catch (RemoteException e) {
   3095         } finally {
   3096             Binder.restoreCallingIdentity(ident);
   3097         }
   3098     }
   3099 
   3100     private boolean isExtStorageEncrypted() {
   3101         String state = SystemProperties.get("vold.decrypt");
   3102         return !"".equals(state);
   3103     }
   3104 
   3105     @Override
   3106     public void enforceCanManageCaCerts(ComponentName who) {
   3107         if (who == null) {
   3108             if (!isCallerDelegatedCertInstaller()) {
   3109                 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
   3110             }
   3111         } else {
   3112             synchronized (this) {
   3113                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   3114             }
   3115         }
   3116     }
   3117 
   3118     private boolean isCallerDelegatedCertInstaller() {
   3119         final int callingUid = Binder.getCallingUid();
   3120         final int userHandle = UserHandle.getUserId(callingUid);
   3121         synchronized (this) {
   3122             final DevicePolicyData policy = getUserData(userHandle);
   3123             if (policy.mDelegatedCertInstallerPackage == null) {
   3124                 return false;
   3125             }
   3126 
   3127             try {
   3128                 int uid = mContext.getPackageManager().getPackageUid(
   3129                         policy.mDelegatedCertInstallerPackage, userHandle);
   3130                 return uid == callingUid;
   3131             } catch (NameNotFoundException e) {
   3132                 return false;
   3133             }
   3134         }
   3135     }
   3136 
   3137     @Override
   3138     public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
   3139         enforceCanManageCaCerts(admin);
   3140 
   3141         byte[] pemCert;
   3142         try {
   3143             X509Certificate cert = parseCert(certBuffer);
   3144             pemCert = Credentials.convertToPem(cert);
   3145         } catch (CertificateException ce) {
   3146             Log.e(LOG_TAG, "Problem converting cert", ce);
   3147             return false;
   3148         } catch (IOException ioe) {
   3149             Log.e(LOG_TAG, "Problem reading cert", ioe);
   3150             return false;
   3151         }
   3152 
   3153         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
   3154         final long id = Binder.clearCallingIdentity();
   3155         try {
   3156             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
   3157             try {
   3158                 keyChainConnection.getService().installCaCertificate(pemCert);
   3159                 return true;
   3160             } catch (RemoteException e) {
   3161                 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
   3162             } finally {
   3163                 keyChainConnection.close();
   3164             }
   3165         } catch (InterruptedException e1) {
   3166             Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
   3167             Thread.currentThread().interrupt();
   3168         } finally {
   3169             Binder.restoreCallingIdentity(id);
   3170         }
   3171         return false;
   3172     }
   3173 
   3174     private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
   3175         CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
   3176         return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
   3177                 certBuffer));
   3178     }
   3179 
   3180     @Override
   3181     public void uninstallCaCerts(ComponentName admin, String[] aliases) {
   3182         enforceCanManageCaCerts(admin);
   3183 
   3184         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
   3185         final long id = Binder.clearCallingIdentity();
   3186         try {
   3187             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
   3188             try {
   3189                 for (int i = 0 ; i < aliases.length; i++) {
   3190                     keyChainConnection.getService().deleteCaCertificate(aliases[i]);
   3191                 }
   3192             } catch (RemoteException e) {
   3193                 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
   3194             } finally {
   3195                 keyChainConnection.close();
   3196             }
   3197         } catch (InterruptedException ie) {
   3198             Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
   3199             Thread.currentThread().interrupt();
   3200         } finally {
   3201             Binder.restoreCallingIdentity(id);
   3202         }
   3203     }
   3204 
   3205     @Override
   3206     public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, String alias) {
   3207         if (who == null) {
   3208             if (!isCallerDelegatedCertInstaller()) {
   3209                 throw new SecurityException("who == null, but caller is not cert installer");
   3210             }
   3211         } else {
   3212             synchronized (this) {
   3213                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   3214             }
   3215         }
   3216         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
   3217         final long id = Binder.clearCallingIdentity();
   3218         try {
   3219           final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
   3220           try {
   3221               IKeyChainService keyChain = keyChainConnection.getService();
   3222               return keyChain.installKeyPair(privKey, cert, alias);
   3223           } catch (RemoteException e) {
   3224               Log.e(LOG_TAG, "Installing certificate", e);
   3225           } finally {
   3226               keyChainConnection.close();
   3227           }
   3228         } catch (InterruptedException e) {
   3229             Log.w(LOG_TAG, "Interrupted while installing certificate", e);
   3230             Thread.currentThread().interrupt();
   3231         } finally {
   3232             Binder.restoreCallingIdentity(id);
   3233         }
   3234         return false;
   3235     }
   3236 
   3237     @Override
   3238     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
   3239             final IBinder response) {
   3240         // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
   3241         if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
   3242             return;
   3243         }
   3244 
   3245         final UserHandle caller = Binder.getCallingUserHandle();
   3246         // If there is a profile owner, redirect to that; otherwise query the device owner.
   3247         ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
   3248         if (aliasChooser == null && caller.isOwner()) {
   3249             ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdmin();
   3250             if (deviceOwnerAdmin != null) {
   3251                 aliasChooser = deviceOwnerAdmin.info.getComponent();
   3252             }
   3253         }
   3254         if (aliasChooser == null) {
   3255             sendPrivateKeyAliasResponse(null, response);
   3256             return;
   3257         }
   3258 
   3259         Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
   3260         intent.setComponent(aliasChooser);
   3261         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
   3262         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
   3263         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
   3264         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
   3265 
   3266         final long id = Binder.clearCallingIdentity();
   3267         try {
   3268             mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
   3269                 @Override
   3270                 public void onReceive(Context context, Intent intent) {
   3271                     final String chosenAlias = getResultData();
   3272                     sendPrivateKeyAliasResponse(chosenAlias, response);
   3273                 }
   3274             }, null, Activity.RESULT_OK, null, null);
   3275         } finally {
   3276             Binder.restoreCallingIdentity(id);
   3277         }
   3278     }
   3279 
   3280     private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
   3281         final IKeyChainAliasCallback keyChainAliasResponse =
   3282                 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
   3283         new AsyncTask<Void, Void, Void>() {
   3284             @Override
   3285             protected Void doInBackground(Void... unused) {
   3286                 try {
   3287                     keyChainAliasResponse.alias(alias);
   3288                 } catch (Exception e) {
   3289                     // Catch everything (not just RemoteException): caller could throw a
   3290                     // RuntimeException back across processes.
   3291                     Log.e(LOG_TAG, "error while responding to callback", e);
   3292                 }
   3293                 return null;
   3294             }
   3295         }.execute();
   3296     }
   3297 
   3298     @Override
   3299     public void setCertInstallerPackage(ComponentName who, String installerPackage)
   3300             throws SecurityException {
   3301         int userHandle = UserHandle.getCallingUserId();
   3302         synchronized (this) {
   3303             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   3304             DevicePolicyData policy = getUserData(userHandle);
   3305             policy.mDelegatedCertInstallerPackage = installerPackage;
   3306             saveSettingsLocked(userHandle);
   3307         }
   3308     }
   3309 
   3310     @Override
   3311     public String getCertInstallerPackage(ComponentName who) throws SecurityException {
   3312         int userHandle = UserHandle.getCallingUserId();
   3313         synchronized (this) {
   3314             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   3315             DevicePolicyData policy = getUserData(userHandle);
   3316             return policy.mDelegatedCertInstallerPackage;
   3317         }
   3318     }
   3319 
   3320     private void wipeDataLocked(boolean wipeExtRequested, String reason) {
   3321         if (wipeExtRequested) {
   3322             StorageManager sm = (StorageManager) mContext.getSystemService(
   3323                     Context.STORAGE_SERVICE);
   3324             sm.wipeAdoptableDisks();
   3325         }
   3326         try {
   3327             RecoverySystem.rebootWipeUserData(mContext, reason);
   3328         } catch (IOException | SecurityException e) {
   3329             Slog.w(LOG_TAG, "Failed requesting data wipe", e);
   3330         }
   3331     }
   3332 
   3333     @Override
   3334     public void wipeData(int flags, final int userHandle) {
   3335         if (!mHasFeature) {
   3336             return;
   3337         }
   3338         enforceCrossUserPermission(userHandle);
   3339         synchronized (this) {
   3340             // This API can only be called by an active device admin,
   3341             // so try to retrieve it to check that the caller is one.
   3342             final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
   3343                     DeviceAdminInfo.USES_POLICY_WIPE_DATA);
   3344 
   3345             final String source;
   3346             final ComponentName cname = admin.info.getComponent();
   3347             if (cname != null) {
   3348                 source = cname.flattenToShortString();
   3349             } else {
   3350                 source = admin.info.getPackageName();
   3351             }
   3352 
   3353             long ident = Binder.clearCallingIdentity();
   3354             try {
   3355                 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
   3356                     boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName())
   3357                             && !hasUserSetupCompleted(userHandle);
   3358                     if (userHandle != UserHandle.USER_OWNER
   3359                             || !(isDeviceOwner(admin.info.getPackageName())
   3360                                     || ownsInitialization)) {
   3361                         throw new SecurityException(
   3362                                "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
   3363                     }
   3364                     PersistentDataBlockManager manager = (PersistentDataBlockManager)
   3365                             mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
   3366                     if (manager != null) {
   3367                         manager.wipe();
   3368                     }
   3369                 }
   3370                 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
   3371                 wipeDeviceOrUserLocked(wipeExtRequested, userHandle,
   3372                         "DevicePolicyManager.wipeData() from " + source);
   3373             } finally {
   3374                 Binder.restoreCallingIdentity(ident);
   3375             }
   3376         }
   3377     }
   3378 
   3379     private void wipeDeviceOrUserLocked(boolean wipeExtRequested, final int userHandle, String reason) {
   3380         if (userHandle == UserHandle.USER_OWNER) {
   3381             wipeDataLocked(wipeExtRequested, reason);
   3382         } else {
   3383             mHandler.post(new Runnable() {
   3384                 @Override
   3385                 public void run() {
   3386                     try {
   3387                         IActivityManager am = ActivityManagerNative.getDefault();
   3388                         if (am.getCurrentUser().id == userHandle) {
   3389                             am.switchUser(UserHandle.USER_OWNER);
   3390                         }
   3391 
   3392                         boolean isManagedProfile = isManagedProfile(userHandle);
   3393                         if (!mUserManager.removeUser(userHandle)) {
   3394                             Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
   3395                         } else if (isManagedProfile) {
   3396                             sendWipeProfileNotification();
   3397                         }
   3398                     } catch (RemoteException re) {
   3399                         // Shouldn't happen
   3400                     }
   3401                 }
   3402             });
   3403         }
   3404     }
   3405 
   3406     private void sendWipeProfileNotification() {
   3407         String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
   3408         Notification notification = new Notification.Builder(mContext)
   3409                 .setSmallIcon(android.R.drawable.stat_sys_warning)
   3410                 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
   3411                 .setContentText(contentText)
   3412                 .setColor(mContext.getColor(R.color.system_notification_accent_color))
   3413                 .setStyle(new Notification.BigTextStyle().bigText(contentText))
   3414                 .build();
   3415         getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
   3416     }
   3417 
   3418     private void clearWipeProfileNotification() {
   3419         getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
   3420     }
   3421 
   3422     @Override
   3423     public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
   3424         if (!mHasFeature) {
   3425             return;
   3426         }
   3427         enforceCrossUserPermission(userHandle);
   3428         mContext.enforceCallingOrSelfPermission(
   3429                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   3430 
   3431         synchronized (this) {
   3432             ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
   3433             if (admin == null) {
   3434                 try {
   3435                     result.sendResult(null);
   3436                 } catch (RemoteException e) {
   3437                 }
   3438                 return;
   3439             }
   3440             Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
   3441             intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
   3442             intent.setComponent(admin.info.getComponent());
   3443             mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
   3444                     null, new BroadcastReceiver() {
   3445                 @Override
   3446                 public void onReceive(Context context, Intent intent) {
   3447                     try {
   3448                         result.sendResult(getResultExtras(false));
   3449                     } catch (RemoteException e) {
   3450                     }
   3451                 }
   3452             }, null, Activity.RESULT_OK, null, null);
   3453         }
   3454     }
   3455 
   3456     @Override
   3457     public void setActivePasswordState(int quality, int length, int letters, int uppercase,
   3458             int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
   3459         if (!mHasFeature) {
   3460             return;
   3461         }
   3462         enforceCrossUserPermission(userHandle);
   3463         enforceNotManagedProfile(userHandle, "set the active password");
   3464 
   3465         mContext.enforceCallingOrSelfPermission(
   3466                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   3467         DevicePolicyData p = getUserData(userHandle);
   3468 
   3469         validateQualityConstant(quality);
   3470 
   3471         synchronized (this) {
   3472             if (p.mActivePasswordQuality != quality || p.mActivePasswordLength != length
   3473                     || p.mFailedPasswordAttempts != 0 || p.mActivePasswordLetters != letters
   3474                     || p.mActivePasswordUpperCase != uppercase
   3475                     || p.mActivePasswordLowerCase != lowercase
   3476                     || p.mActivePasswordNumeric != numbers
   3477                     || p.mActivePasswordSymbols != symbols
   3478                     || p.mActivePasswordNonLetter != nonletter) {
   3479                 long ident = Binder.clearCallingIdentity();
   3480                 try {
   3481                     p.mActivePasswordQuality = quality;
   3482                     p.mActivePasswordLength = length;
   3483                     p.mActivePasswordLetters = letters;
   3484                     p.mActivePasswordLowerCase = lowercase;
   3485                     p.mActivePasswordUpperCase = uppercase;
   3486                     p.mActivePasswordNumeric = numbers;
   3487                     p.mActivePasswordSymbols = symbols;
   3488                     p.mActivePasswordNonLetter = nonletter;
   3489                     p.mFailedPasswordAttempts = 0;
   3490                     saveSettingsLocked(userHandle);
   3491                     updatePasswordExpirationsLocked(userHandle);
   3492                     setExpirationAlarmCheckLocked(mContext, p);
   3493                     sendAdminCommandToSelfAndProfilesLocked(
   3494                             DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
   3495                             DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
   3496                 } finally {
   3497                     Binder.restoreCallingIdentity(ident);
   3498                 }
   3499             }
   3500         }
   3501     }
   3502 
   3503     /**
   3504      * Called any time the device password is updated. Resets all password expiration clocks.
   3505      */
   3506     private void updatePasswordExpirationsLocked(int userHandle) {
   3507             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   3508             for (UserInfo userInfo : profiles) {
   3509                 int profileId = userInfo.id;
   3510                 DevicePolicyData policy = getUserDataUnchecked(profileId);
   3511                 final int N = policy.mAdminList.size();
   3512                 if (N > 0) {
   3513                     for (int i=0; i<N; i++) {
   3514                         ActiveAdmin admin = policy.mAdminList.get(i);
   3515                         if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
   3516                             long timeout = admin.passwordExpirationTimeout;
   3517                             long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
   3518                             admin.passwordExpirationDate = expiration;
   3519                         }
   3520                     }
   3521                 }
   3522                 saveSettingsLocked(profileId);
   3523             }
   3524     }
   3525 
   3526     @Override
   3527     public void reportFailedPasswordAttempt(int userHandle) {
   3528         enforceCrossUserPermission(userHandle);
   3529         enforceNotManagedProfile(userHandle, "report failed password attempt");
   3530         mContext.enforceCallingOrSelfPermission(
   3531                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   3532 
   3533         long ident = Binder.clearCallingIdentity();
   3534         try {
   3535             boolean wipeData = false;
   3536             int identifier = 0;
   3537             synchronized (this) {
   3538                 DevicePolicyData policy = getUserData(userHandle);
   3539                 policy.mFailedPasswordAttempts++;
   3540                 saveSettingsLocked(userHandle);
   3541                 if (mHasFeature) {
   3542                     ActiveAdmin strictestAdmin =
   3543                             getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
   3544                     int max = strictestAdmin != null
   3545                             ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
   3546                     if (max > 0 && policy.mFailedPasswordAttempts >= max) {
   3547                         // Wipe the user/profile associated with the policy that was violated. This
   3548                         // is not necessarily calling user: if the policy that fired was from a
   3549                         // managed profile rather than the main user profile, we wipe former only.
   3550                         wipeData = true;
   3551                         identifier = strictestAdmin.getUserHandle().getIdentifier();
   3552                     }
   3553                     sendAdminCommandToSelfAndProfilesLocked(
   3554                             DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
   3555                             DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
   3556                 }
   3557             }
   3558             if (wipeData) {
   3559                 // Call without holding lock.
   3560                 wipeDeviceOrUserLocked(false, identifier,
   3561                         "reportFailedPasswordAttempt()");
   3562             }
   3563         } finally {
   3564             Binder.restoreCallingIdentity(ident);
   3565         }
   3566     }
   3567 
   3568     @Override
   3569     public void reportSuccessfulPasswordAttempt(int userHandle) {
   3570         enforceCrossUserPermission(userHandle);
   3571         mContext.enforceCallingOrSelfPermission(
   3572                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
   3573 
   3574         synchronized (this) {
   3575             DevicePolicyData policy = getUserData(userHandle);
   3576             if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
   3577                 long ident = Binder.clearCallingIdentity();
   3578                 try {
   3579                     policy.mFailedPasswordAttempts = 0;
   3580                     policy.mPasswordOwner = -1;
   3581                     saveSettingsLocked(userHandle);
   3582                     if (mHasFeature) {
   3583                         sendAdminCommandToSelfAndProfilesLocked(
   3584                                 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
   3585                                 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
   3586                     }
   3587                 } finally {
   3588                     Binder.restoreCallingIdentity(ident);
   3589                 }
   3590             }
   3591         }
   3592     }
   3593 
   3594     @Override
   3595     public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
   3596             String exclusionList) {
   3597         if (!mHasFeature) {
   3598             return null;
   3599         }
   3600         synchronized(this) {
   3601             Preconditions.checkNotNull(who, "ComponentName is null");
   3602 
   3603             // Only check if owner has set global proxy. We don't allow other users to set it.
   3604             DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
   3605             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   3606                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
   3607 
   3608             // Scan through active admins and find if anyone has already
   3609             // set the global proxy.
   3610             Set<ComponentName> compSet = policy.mAdminMap.keySet();
   3611             for (ComponentName component : compSet) {
   3612                 ActiveAdmin ap = policy.mAdminMap.get(component);
   3613                 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
   3614                     // Another admin already sets the global proxy
   3615                     // Return it to the caller.
   3616                     return component;
   3617                 }
   3618             }
   3619 
   3620             // If the user is not the owner, don't set the global proxy. Fail silently.
   3621             if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
   3622                 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
   3623                         + UserHandle.getCallingUserId() + " is not permitted.");
   3624                 return null;
   3625             }
   3626             if (proxySpec == null) {
   3627                 admin.specifiesGlobalProxy = false;
   3628                 admin.globalProxySpec = null;
   3629                 admin.globalProxyExclusionList = null;
   3630             } else {
   3631 
   3632                 admin.specifiesGlobalProxy = true;
   3633                 admin.globalProxySpec = proxySpec;
   3634                 admin.globalProxyExclusionList = exclusionList;
   3635             }
   3636 
   3637             // Reset the global proxy accordingly
   3638             // Do this using system permissions, as apps cannot write to secure settings
   3639             long origId = Binder.clearCallingIdentity();
   3640             try {
   3641                 resetGlobalProxyLocked(policy);
   3642             } finally {
   3643                 Binder.restoreCallingIdentity(origId);
   3644             }
   3645             return null;
   3646         }
   3647     }
   3648 
   3649     @Override
   3650     public ComponentName getGlobalProxyAdmin(int userHandle) {
   3651         if (!mHasFeature) {
   3652             return null;
   3653         }
   3654         enforceCrossUserPermission(userHandle);
   3655         synchronized(this) {
   3656             DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
   3657             // Scan through active admins and find if anyone has already
   3658             // set the global proxy.
   3659             final int N = policy.mAdminList.size();
   3660             for (int i = 0; i < N; i++) {
   3661                 ActiveAdmin ap = policy.mAdminList.get(i);
   3662                 if (ap.specifiesGlobalProxy) {
   3663                     // Device admin sets the global proxy
   3664                     // Return it to the caller.
   3665                     return ap.info.getComponent();
   3666                 }
   3667             }
   3668         }
   3669         // No device admin sets the global proxy.
   3670         return null;
   3671     }
   3672 
   3673     @Override
   3674     public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
   3675         synchronized (this) {
   3676             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   3677         }
   3678         long token = Binder.clearCallingIdentity();
   3679         try {
   3680             ConnectivityManager connectivityManager = (ConnectivityManager)
   3681                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
   3682             connectivityManager.setGlobalProxy(proxyInfo);
   3683         } finally {
   3684             Binder.restoreCallingIdentity(token);
   3685         }
   3686     }
   3687 
   3688     private void resetGlobalProxyLocked(DevicePolicyData policy) {
   3689         final int N = policy.mAdminList.size();
   3690         for (int i = 0; i < N; i++) {
   3691             ActiveAdmin ap = policy.mAdminList.get(i);
   3692             if (ap.specifiesGlobalProxy) {
   3693                 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
   3694                 return;
   3695             }
   3696         }
   3697         // No device admins defining global proxies - reset global proxy settings to none
   3698         saveGlobalProxyLocked(null, null);
   3699     }
   3700 
   3701     private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
   3702         if (exclusionList == null) {
   3703             exclusionList = "";
   3704         }
   3705         if (proxySpec == null) {
   3706             proxySpec = "";
   3707         }
   3708         // Remove white spaces
   3709         proxySpec = proxySpec.trim();
   3710         String data[] = proxySpec.split(":");
   3711         int proxyPort = 8080;
   3712         if (data.length > 1) {
   3713             try {
   3714                 proxyPort = Integer.parseInt(data[1]);
   3715             } catch (NumberFormatException e) {}
   3716         }
   3717         exclusionList = exclusionList.trim();
   3718         ContentResolver res = mContext.getContentResolver();
   3719 
   3720         ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
   3721         if (!proxyProperties.isValid()) {
   3722             Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
   3723             return;
   3724         }
   3725         Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
   3726         Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
   3727         Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
   3728                 exclusionList);
   3729     }
   3730 
   3731     /**
   3732      * Set the storage encryption request for a single admin.  Returns the new total request
   3733      * status (for all admins).
   3734      */
   3735     @Override
   3736     public int setStorageEncryption(ComponentName who, boolean encrypt) {
   3737         if (!mHasFeature) {
   3738             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
   3739         }
   3740         Preconditions.checkNotNull(who, "ComponentName is null");
   3741         final int userHandle = UserHandle.getCallingUserId();
   3742         synchronized (this) {
   3743             // Check for permissions
   3744             // Only owner can set storage encryption
   3745             if (userHandle != UserHandle.USER_OWNER
   3746                     || UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
   3747                 Slog.w(LOG_TAG, "Only owner is allowed to set storage encryption. User "
   3748                         + UserHandle.getCallingUserId() + " is not permitted.");
   3749                 return 0;
   3750             }
   3751 
   3752             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   3753                     DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
   3754 
   3755             // Quick exit:  If the filesystem does not support encryption, we can exit early.
   3756             if (!isEncryptionSupported()) {
   3757                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
   3758             }
   3759 
   3760             // (1) Record the value for the admin so it's sticky
   3761             if (ap.encryptionRequested != encrypt) {
   3762                 ap.encryptionRequested = encrypt;
   3763                 saveSettingsLocked(userHandle);
   3764             }
   3765 
   3766             DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
   3767             // (2) Compute "max" for all admins
   3768             boolean newRequested = false;
   3769             final int N = policy.mAdminList.size();
   3770             for (int i = 0; i < N; i++) {
   3771                 newRequested |= policy.mAdminList.get(i).encryptionRequested;
   3772             }
   3773 
   3774             // Notify OS of new request
   3775             setEncryptionRequested(newRequested);
   3776 
   3777             // Return the new global request status
   3778             return newRequested
   3779                     ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
   3780                     : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
   3781         }
   3782     }
   3783 
   3784     /**
   3785      * Get the current storage encryption request status for a given admin, or aggregate of all
   3786      * active admins.
   3787      */
   3788     @Override
   3789     public boolean getStorageEncryption(ComponentName who, int userHandle) {
   3790         if (!mHasFeature) {
   3791             return false;
   3792         }
   3793         enforceCrossUserPermission(userHandle);
   3794         synchronized (this) {
   3795             // Check for permissions if a particular caller is specified
   3796             if (who != null) {
   3797                 // When checking for a single caller, status is based on caller's request
   3798                 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
   3799                 return ap != null ? ap.encryptionRequested : false;
   3800             }
   3801 
   3802             // If no particular caller is specified, return the aggregate set of requests.
   3803             // This is short circuited by returning true on the first hit.
   3804             DevicePolicyData policy = getUserData(userHandle);
   3805             final int N = policy.mAdminList.size();
   3806             for (int i = 0; i < N; i++) {
   3807                 if (policy.mAdminList.get(i).encryptionRequested) {
   3808                     return true;
   3809                 }
   3810             }
   3811             return false;
   3812         }
   3813     }
   3814 
   3815     /**
   3816      * Get the current encryption status of the device.
   3817      */
   3818     @Override
   3819     public int getStorageEncryptionStatus(int userHandle) {
   3820         if (!mHasFeature) {
   3821             // Ok to return current status.
   3822         }
   3823         enforceCrossUserPermission(userHandle);
   3824         return getEncryptionStatus();
   3825     }
   3826 
   3827     /**
   3828      * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
   3829      */
   3830     private boolean isEncryptionSupported() {
   3831         // Note, this can be implemented as
   3832         //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
   3833         // But is provided as a separate internal method if there's a faster way to do a
   3834         // simple check for supported-or-not.
   3835         return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
   3836     }
   3837 
   3838     /**
   3839      * Hook to low-levels:  Reporting the current status of encryption.
   3840      * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
   3841      * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
   3842      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, or
   3843      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
   3844      */
   3845     private int getEncryptionStatus() {
   3846         String status = SystemProperties.get("ro.crypto.state", "unsupported");
   3847         if ("encrypted".equalsIgnoreCase(status)) {
   3848             final long token = Binder.clearCallingIdentity();
   3849             try {
   3850                 return LockPatternUtils.isDeviceEncrypted()
   3851                         ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
   3852                         : DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
   3853             } finally {
   3854                 Binder.restoreCallingIdentity(token);
   3855             }
   3856         } else if ("unencrypted".equalsIgnoreCase(status)) {
   3857             return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
   3858         } else {
   3859             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
   3860         }
   3861     }
   3862 
   3863     /**
   3864      * Hook to low-levels:  If needed, record the new admin setting for encryption.
   3865      */
   3866     private void setEncryptionRequested(boolean encrypt) {
   3867     }
   3868 
   3869 
   3870     /**
   3871      * Set whether the screen capture is disabled for the user managed by the specified admin.
   3872      */
   3873     @Override
   3874     public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
   3875         if (!mHasFeature) {
   3876             return;
   3877         }
   3878         Preconditions.checkNotNull(who, "ComponentName is null");
   3879         final int userHandle = UserHandle.getCallingUserId();
   3880         synchronized (this) {
   3881             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   3882                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   3883             if (ap.disableScreenCapture != disabled) {
   3884                 ap.disableScreenCapture = disabled;
   3885                 saveSettingsLocked(userHandle);
   3886                 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
   3887             }
   3888         }
   3889     }
   3890 
   3891     /**
   3892      * Returns whether or not screen capture is disabled for a given admin, or disabled for any
   3893      * active admin (if given admin is null).
   3894      */
   3895     @Override
   3896     public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
   3897         if (!mHasFeature) {
   3898             return false;
   3899         }
   3900         synchronized (this) {
   3901             if (who != null) {
   3902                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   3903                 return (admin != null) ? admin.disableScreenCapture : false;
   3904             }
   3905 
   3906             DevicePolicyData policy = getUserData(userHandle);
   3907             final int N = policy.mAdminList.size();
   3908             for (int i = 0; i < N; i++) {
   3909                 ActiveAdmin admin = policy.mAdminList.get(i);
   3910                 if (admin.disableScreenCapture) {
   3911                     return true;
   3912                 }
   3913             }
   3914             return false;
   3915         }
   3916     }
   3917 
   3918     private void updateScreenCaptureDisabledInWindowManager(int userHandle, boolean disabled) {
   3919         long ident = Binder.clearCallingIdentity();
   3920         try {
   3921             getWindowManager().setScreenCaptureDisabled(userHandle, disabled);
   3922         } catch (RemoteException e) {
   3923             Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
   3924         } finally {
   3925             Binder.restoreCallingIdentity(ident);
   3926         }
   3927     }
   3928 
   3929     /**
   3930      * Set whether auto time is required by the specified admin (must be device owner).
   3931      */
   3932     @Override
   3933     public void setAutoTimeRequired(ComponentName who, boolean required) {
   3934         if (!mHasFeature) {
   3935             return;
   3936         }
   3937         Preconditions.checkNotNull(who, "ComponentName is null");
   3938         final int userHandle = UserHandle.getCallingUserId();
   3939         synchronized (this) {
   3940             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   3941                     DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   3942             if (admin.requireAutoTime != required) {
   3943                 admin.requireAutoTime = required;
   3944                 saveSettingsLocked(userHandle);
   3945             }
   3946         }
   3947 
   3948         // Turn AUTO_TIME on in settings if it is required
   3949         if (required) {
   3950             long ident = Binder.clearCallingIdentity();
   3951             try {
   3952                 Settings.Global.putInt(mContext.getContentResolver(),
   3953                         Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
   3954             } finally {
   3955                 Binder.restoreCallingIdentity(ident);
   3956             }
   3957         }
   3958     }
   3959 
   3960     /**
   3961      * Returns whether or not auto time is required by the device owner.
   3962      */
   3963     @Override
   3964     public boolean getAutoTimeRequired() {
   3965         if (!mHasFeature) {
   3966             return false;
   3967         }
   3968         synchronized (this) {
   3969             ActiveAdmin deviceOwner = getDeviceOwnerAdmin();
   3970             return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
   3971         }
   3972     }
   3973 
   3974     /**
   3975      * The system property used to share the state of the camera. The native camera service
   3976      * is expected to read this property and act accordingly. The userId should be appended
   3977      * to this key.
   3978      */
   3979     public static final String SYSTEM_PROP_DISABLE_CAMERA_PREFIX = "sys.secpolicy.camera.off_";
   3980 
   3981     /**
   3982      * Disables all device cameras according to the specified admin.
   3983      */
   3984     @Override
   3985     public void setCameraDisabled(ComponentName who, boolean disabled) {
   3986         if (!mHasFeature) {
   3987             return;
   3988         }
   3989         Preconditions.checkNotNull(who, "ComponentName is null");
   3990         final int userHandle = UserHandle.getCallingUserId();
   3991         synchronized (this) {
   3992             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   3993                     DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
   3994             if (ap.disableCamera != disabled) {
   3995                 ap.disableCamera = disabled;
   3996                 saveSettingsLocked(userHandle);
   3997             }
   3998             syncDeviceCapabilitiesLocked(getUserData(userHandle));
   3999         }
   4000     }
   4001 
   4002     /**
   4003      * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
   4004      * active admins.
   4005      */
   4006     @Override
   4007     public boolean getCameraDisabled(ComponentName who, int userHandle) {
   4008         if (!mHasFeature) {
   4009             return false;
   4010         }
   4011         synchronized (this) {
   4012             if (who != null) {
   4013                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   4014                 return (admin != null) ? admin.disableCamera : false;
   4015             }
   4016 
   4017             DevicePolicyData policy = getUserData(userHandle);
   4018             // Determine whether or not the device camera is disabled for any active admins.
   4019             final int N = policy.mAdminList.size();
   4020             for (int i = 0; i < N; i++) {
   4021                 ActiveAdmin admin = policy.mAdminList.get(i);
   4022                 if (admin.disableCamera) {
   4023                     return true;
   4024                 }
   4025             }
   4026             return false;
   4027         }
   4028     }
   4029 
   4030     /**
   4031      * Selectively disable keyguard features.
   4032      */
   4033     @Override
   4034     public void setKeyguardDisabledFeatures(ComponentName who, int which) {
   4035         if (!mHasFeature) {
   4036             return;
   4037         }
   4038         Preconditions.checkNotNull(who, "ComponentName is null");
   4039         final int userHandle = UserHandle.getCallingUserId();
   4040         if (isManagedProfile(userHandle)) {
   4041             which = which & PROFILE_KEYGUARD_FEATURES;
   4042         }
   4043         synchronized (this) {
   4044             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   4045                     DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
   4046             if (ap.disabledKeyguardFeatures != which) {
   4047                 ap.disabledKeyguardFeatures = which;
   4048                 saveSettingsLocked(userHandle);
   4049             }
   4050             syncDeviceCapabilitiesLocked(getUserData(userHandle));
   4051         }
   4052     }
   4053 
   4054     /**
   4055      * Gets the disabled state for features in keyguard for the given admin,
   4056      * or the aggregate of all active admins if who is null.
   4057      */
   4058     @Override
   4059     public int getKeyguardDisabledFeatures(ComponentName who, int userHandle) {
   4060         if (!mHasFeature) {
   4061             return 0;
   4062         }
   4063         enforceCrossUserPermission(userHandle);
   4064         long ident = Binder.clearCallingIdentity();
   4065         try {
   4066             synchronized (this) {
   4067                 if (who != null) {
   4068                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
   4069                     return (admin != null) ? admin.disabledKeyguardFeatures : 0;
   4070                 }
   4071 
   4072                 UserInfo user = mUserManager.getUserInfo(userHandle);
   4073                 final List<UserInfo> profiles;
   4074                 if (user.isManagedProfile()) {
   4075                     // If we are being asked about a managed profile just return
   4076                     // keyguard features disabled by admins in the profile.
   4077                     profiles = new ArrayList<UserInfo>(1);
   4078                     profiles.add(user);
   4079                 } else {
   4080                     // Otherwise return those set by admins in the user
   4081                     // and its profiles.
   4082                     profiles = mUserManager.getProfiles(userHandle);
   4083                 }
   4084 
   4085                 // Determine which keyguard features are disabled by any active admin.
   4086                 int which = 0;
   4087                 for (UserInfo userInfo : profiles) {
   4088                     DevicePolicyData policy = getUserData(userInfo.id);
   4089                     final int N = policy.mAdminList.size();
   4090                     for (int i = 0; i < N; i++) {
   4091                         ActiveAdmin admin = policy.mAdminList.get(i);
   4092                         if (userInfo.id == userHandle || !userInfo.isManagedProfile()) {
   4093                             // If we are being asked explictly about this user
   4094                             // return all disabled features even if its a managed profile.
   4095                             which |= admin.disabledKeyguardFeatures;
   4096                         } else {
   4097                             // Otherwise a managed profile is only allowed to disable
   4098                             // some features on the parent user.
   4099                             which |= (admin.disabledKeyguardFeatures
   4100                                     & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
   4101                         }
   4102                     }
   4103                 }
   4104                 return which;
   4105             }
   4106         } finally {
   4107             Binder.restoreCallingIdentity(ident);
   4108         }
   4109     }
   4110 
   4111     @Override
   4112     public boolean setDeviceOwner(String packageName, String ownerName) {
   4113         if (!mHasFeature) {
   4114             return false;
   4115         }
   4116         if (packageName == null
   4117                 || !DeviceOwner.isInstalled(packageName, mContext.getPackageManager())) {
   4118             throw new IllegalArgumentException("Invalid package name " + packageName
   4119                     + " for device owner");
   4120         }
   4121         synchronized (this) {
   4122             enforceCanSetDeviceOwner();
   4123 
   4124             // Shutting down backup manager service permanently.
   4125             long ident = Binder.clearCallingIdentity();
   4126             try {
   4127                 IBackupManager ibm = IBackupManager.Stub.asInterface(
   4128                         ServiceManager.getService(Context.BACKUP_SERVICE));
   4129                 ibm.setBackupServiceActive(UserHandle.USER_OWNER, false);
   4130             } catch (RemoteException e) {
   4131                 throw new IllegalStateException("Failed deactivating backup service.", e);
   4132             } finally {
   4133                 Binder.restoreCallingIdentity(ident);
   4134             }
   4135 
   4136             if (mDeviceOwner == null) {
   4137                 // Device owner is not set and does not exist, set it.
   4138                 mDeviceOwner = DeviceOwner.createWithDeviceOwner(packageName, ownerName);
   4139             } else {
   4140                 // Device owner state already exists, update it.
   4141                 mDeviceOwner.setDeviceOwner(packageName, ownerName);
   4142             }
   4143             mDeviceOwner.writeOwnerFile();
   4144             updateDeviceOwnerLocked();
   4145             Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
   4146 
   4147             ident = Binder.clearCallingIdentity();
   4148             try {
   4149                 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
   4150             } finally {
   4151                 Binder.restoreCallingIdentity(ident);
   4152             }
   4153             return true;
   4154         }
   4155     }
   4156 
   4157     @Override
   4158     public boolean isDeviceOwner(String packageName) {
   4159         if (!mHasFeature) {
   4160             return false;
   4161         }
   4162         synchronized (this) {
   4163             return mDeviceOwner != null
   4164                     && mDeviceOwner.hasDeviceOwner()
   4165                     && mDeviceOwner.getDeviceOwnerPackageName().equals(packageName);
   4166         }
   4167     }
   4168 
   4169     @Override
   4170     public String getDeviceOwner() {
   4171         if (!mHasFeature) {
   4172             return null;
   4173         }
   4174         synchronized (this) {
   4175             if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
   4176                 return mDeviceOwner.getDeviceOwnerPackageName();
   4177             }
   4178         }
   4179         return null;
   4180     }
   4181 
   4182     @Override
   4183     public String getDeviceOwnerName() {
   4184         if (!mHasFeature) {
   4185             return null;
   4186         }
   4187         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
   4188         synchronized (this) {
   4189             if (mDeviceOwner == null || !mDeviceOwner.hasDeviceOwner()) {
   4190                 return null;
   4191             }
   4192             String deviceOwnerPackage = mDeviceOwner.getDeviceOwnerPackageName();
   4193             return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_OWNER);
   4194         }
   4195     }
   4196 
   4197     // Returns the active device owner or null if there is no device owner.
   4198     private ActiveAdmin getDeviceOwnerAdmin() {
   4199         String deviceOwnerPackageName = getDeviceOwner();
   4200         if (deviceOwnerPackageName == null) {
   4201             return null;
   4202         }
   4203 
   4204         DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
   4205         final int n = policy.mAdminList.size();
   4206         for (int i = 0; i < n; i++) {
   4207             ActiveAdmin admin = policy.mAdminList.get(i);
   4208             if (deviceOwnerPackageName.equals(admin.info.getPackageName())) {
   4209                 return admin;
   4210             }
   4211         }
   4212         return null;
   4213     }
   4214 
   4215     @Override
   4216     public void clearDeviceOwner(String packageName) {
   4217         Preconditions.checkNotNull(packageName, "packageName is null");
   4218         try {
   4219             int uid = mContext.getPackageManager().getPackageUid(packageName, 0);
   4220             if (uid != Binder.getCallingUid()) {
   4221                 throw new SecurityException("Invalid packageName");
   4222             }
   4223         } catch (NameNotFoundException e) {
   4224             throw new SecurityException(e);
   4225         }
   4226         if (!isDeviceOwner(packageName)) {
   4227             throw new SecurityException("clearDeviceOwner can only be called by the device owner");
   4228         }
   4229         synchronized (this) {
   4230             clearUserPoliciesLocked(new UserHandle(UserHandle.USER_OWNER));
   4231             if (mDeviceOwner != null) {
   4232                 mDeviceOwner.clearDeviceOwner();
   4233                 mDeviceOwner.writeOwnerFile();
   4234                 updateDeviceOwnerLocked();
   4235             }
   4236         }
   4237     }
   4238 
   4239     @Override
   4240     public boolean setDeviceInitializer(ComponentName who, ComponentName initializer) {
   4241         if (!mHasFeature) {
   4242             return false;
   4243         }
   4244         if (initializer == null || !DeviceOwner.isInstalled(
   4245                 initializer.getPackageName(), mContext.getPackageManager())) {
   4246             throw new IllegalArgumentException("Invalid component name " + initializer
   4247                     + " for device initializer");
   4248         }
   4249         boolean isInitializerSystemApp;
   4250         try {
   4251             isInitializerSystemApp = isSystemApp(AppGlobals.getPackageManager(),
   4252                     initializer.getPackageName(), Binder.getCallingUserHandle().getIdentifier());
   4253         } catch (RemoteException | IllegalArgumentException e) {
   4254             isInitializerSystemApp = false;
   4255             Slog.e(LOG_TAG, "Fail to check if device initialzer is system app.", e);
   4256         }
   4257         if (!isInitializerSystemApp) {
   4258             throw new IllegalArgumentException("Only system app can be set as device initializer.");
   4259         }
   4260         synchronized (this) {
   4261             enforceCanSetDeviceInitializer(who);
   4262 
   4263             if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
   4264                 throw new IllegalStateException(
   4265                         "Trying to set device initializer but device initializer is already set.");
   4266             }
   4267 
   4268             if (mDeviceOwner == null) {
   4269                 // Device owner state does not exist, create it.
   4270                 mDeviceOwner = DeviceOwner.createWithDeviceInitializer(initializer);
   4271             } else {
   4272                 // Device owner already exists, update it.
   4273                 mDeviceOwner.setDeviceInitializer(initializer);
   4274             }
   4275 
   4276             addDeviceInitializerToLockTaskPackagesLocked(UserHandle.USER_OWNER);
   4277             mDeviceOwner.writeOwnerFile();
   4278             return true;
   4279         }
   4280     }
   4281 
   4282     private void enforceCanSetDeviceInitializer(ComponentName who) {
   4283         if (who == null) {
   4284             mContext.enforceCallingOrSelfPermission(
   4285                     android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
   4286             if (hasUserSetupCompleted(UserHandle.USER_OWNER)) {
   4287                 throw new IllegalStateException(
   4288                         "Trying to set device initializer but device is already provisioned.");
   4289             }
   4290         } else {
   4291             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   4292         }
   4293     }
   4294 
   4295     @Override
   4296     public boolean isDeviceInitializer(String packageName) {
   4297         if (!mHasFeature) {
   4298             return false;
   4299         }
   4300         synchronized (this) {
   4301             return mDeviceOwner != null
   4302                     && mDeviceOwner.hasDeviceInitializer()
   4303                     && mDeviceOwner.getDeviceInitializerPackageName().equals(packageName);
   4304         }
   4305     }
   4306 
   4307     @Override
   4308     public String getDeviceInitializer() {
   4309         if (!mHasFeature) {
   4310             return null;
   4311         }
   4312         synchronized (this) {
   4313             if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
   4314                 return mDeviceOwner.getDeviceInitializerPackageName();
   4315             }
   4316         }
   4317         return null;
   4318     }
   4319 
   4320     @Override
   4321     public ComponentName getDeviceInitializerComponent() {
   4322         if (!mHasFeature) {
   4323             return null;
   4324         }
   4325         synchronized (this) {
   4326             if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
   4327                 return mDeviceOwner.getDeviceInitializerComponent();
   4328             }
   4329         }
   4330         return null;
   4331     }
   4332 
   4333     @Override
   4334     public void clearDeviceInitializer(ComponentName who) {
   4335         if (!mHasFeature) {
   4336             return;
   4337         }
   4338         Preconditions.checkNotNull(who, "ComponentName is null");
   4339 
   4340         ActiveAdmin admin = getActiveAdminUncheckedLocked(who, UserHandle.getCallingUserId());
   4341 
   4342         if (admin.getUid() != Binder.getCallingUid()) {
   4343             throw new SecurityException("Admin " + who + " is not owned by uid "
   4344                     + Binder.getCallingUid());
   4345         }
   4346 
   4347         if (!isDeviceInitializer(admin.info.getPackageName())
   4348                 && !isDeviceOwner(admin.info.getPackageName())) {
   4349             throw new SecurityException(
   4350                     "clearDeviceInitializer can only be called by the device initializer/owner");
   4351         }
   4352         synchronized (this) {
   4353             long ident = Binder.clearCallingIdentity();
   4354             try {
   4355                 if (mDeviceOwner != null) {
   4356                     mDeviceOwner.clearDeviceInitializer();
   4357                     mDeviceOwner.writeOwnerFile();
   4358                 }
   4359             } finally {
   4360                 Binder.restoreCallingIdentity(ident);
   4361             }
   4362         }
   4363     }
   4364 
   4365     @Override
   4366     public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
   4367         if (!mHasFeature) {
   4368             return false;
   4369         }
   4370         if (who == null
   4371                 || !DeviceOwner.isInstalledForUser(who.getPackageName(), userHandle)) {
   4372             throw new IllegalArgumentException("Component " + who
   4373                     + " not installed for userId:" + userHandle);
   4374         }
   4375         synchronized (this) {
   4376             enforceCanSetProfileOwner(userHandle);
   4377             if (mDeviceOwner == null) {
   4378                 // Device owner state does not exist, create it.
   4379                 mDeviceOwner = DeviceOwner.createWithProfileOwner(who, ownerName,
   4380                         userHandle);
   4381             } else {
   4382                 // Device owner state already exists, update it.
   4383                 mDeviceOwner.setProfileOwner(who, ownerName, userHandle);
   4384             }
   4385             mDeviceOwner.writeOwnerFile();
   4386             return true;
   4387         }
   4388     }
   4389 
   4390     @Override
   4391     public void clearProfileOwner(ComponentName who) {
   4392         if (!mHasFeature) {
   4393             return;
   4394         }
   4395         UserHandle callingUser = Binder.getCallingUserHandle();
   4396         // Check if this is the profile owner who is calling
   4397         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4398         synchronized (this) {
   4399             clearUserPoliciesLocked(callingUser);
   4400             if (mDeviceOwner != null) {
   4401                 mDeviceOwner.removeProfileOwner(callingUser.getIdentifier());
   4402                 mDeviceOwner.writeOwnerFile();
   4403             }
   4404         }
   4405     }
   4406 
   4407     private void clearUserPoliciesLocked(UserHandle userHandle) {
   4408         int userId = userHandle.getIdentifier();
   4409         // Reset some of the user-specific policies
   4410         DevicePolicyData policy = getUserData(userId);
   4411         policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
   4412         policy.mDelegatedCertInstallerPackage = null;
   4413         policy.mStatusBarDisabled = false;
   4414         saveSettingsLocked(userId);
   4415 
   4416         final long ident = Binder.clearCallingIdentity();
   4417         try {
   4418             clearUserRestrictions(userHandle);
   4419             AppGlobals.getPackageManager().updatePermissionFlagsForAllApps(
   4420                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
   4421                     0  /* flagValues */, userHandle.getIdentifier());
   4422         } catch (RemoteException re) {
   4423         } finally {
   4424             Binder.restoreCallingIdentity(ident);
   4425         }
   4426     }
   4427 
   4428 
   4429     private void clearUserRestrictions(UserHandle userHandle) {
   4430         Bundle userRestrictions = mUserManager.getUserRestrictions();
   4431         mUserManager.setUserRestrictions(new Bundle(), userHandle);
   4432         IAudioService iAudioService = IAudioService.Stub.asInterface(
   4433                 ServiceManager.getService(Context.AUDIO_SERVICE));
   4434         if (userRestrictions.getBoolean(UserManager.DISALLOW_ADJUST_VOLUME)) {
   4435             try {
   4436                 iAudioService.setMasterMute(true, 0, mContext.getPackageName(),
   4437                         userHandle.getIdentifier());
   4438             } catch (RemoteException e) {
   4439                 // Not much we can do here.
   4440             }
   4441         }
   4442         if (userRestrictions.getBoolean(UserManager.DISALLOW_UNMUTE_MICROPHONE)) {
   4443             try {
   4444                 iAudioService.setMicrophoneMute(true, mContext.getPackageName(),
   4445                         userHandle.getIdentifier());
   4446             } catch (RemoteException e) {
   4447                 // Not much we can do here.
   4448             }
   4449         }
   4450     }
   4451 
   4452     @Override
   4453     public boolean hasUserSetupCompleted() {
   4454         return hasUserSetupCompleted(UserHandle.getCallingUserId());
   4455     }
   4456 
   4457     private boolean hasUserSetupCompleted(int userHandle) {
   4458         if (!mHasFeature) {
   4459             return true;
   4460         }
   4461         DevicePolicyData policy = getUserData(userHandle);
   4462         // If policy is null, return true, else check if the setup has completed.
   4463         return policy == null || policy.mUserSetupComplete;
   4464     }
   4465 
   4466     @Override
   4467     public boolean setUserEnabled(ComponentName who) {
   4468         if (!mHasFeature) {
   4469             return false;
   4470         }
   4471         synchronized (this) {
   4472             if (who == null) {
   4473                 throw new NullPointerException("ComponentName is null");
   4474             }
   4475             int userId = UserHandle.getCallingUserId();
   4476 
   4477             ActiveAdmin activeAdmin =
   4478                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4479             if (!isDeviceInitializer(activeAdmin.info.getPackageName())) {
   4480                 throw new SecurityException(
   4481                         "This method can only be called by device initializers");
   4482             }
   4483 
   4484             long id = Binder.clearCallingIdentity();
   4485             try {
   4486                 if (!isDeviceOwner(activeAdmin.info.getPackageName())) {
   4487                     IPackageManager ipm = AppGlobals.getPackageManager();
   4488                     ipm.setComponentEnabledSetting(who,
   4489                             PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
   4490                             PackageManager.DONT_KILL_APP, userId);
   4491 
   4492                     removeActiveAdmin(who, userId);
   4493                 }
   4494 
   4495                 if (userId == UserHandle.USER_OWNER) {
   4496                     Settings.Global.putInt(mContext.getContentResolver(),
   4497                             Settings.Global.DEVICE_PROVISIONED, 1);
   4498                 }
   4499                 Settings.Secure.putIntForUser(mContext.getContentResolver(),
   4500                         Settings.Secure.USER_SETUP_COMPLETE, 1, userId);
   4501             } catch (RemoteException e) {
   4502                 Log.i(LOG_TAG, "Can't talk to package manager", e);
   4503                 return false;
   4504             } finally {
   4505                 restoreCallingIdentity(id);
   4506             }
   4507             return true;
   4508         }
   4509     }
   4510 
   4511     @Override
   4512     public void setProfileEnabled(ComponentName who) {
   4513         if (!mHasFeature) {
   4514             return;
   4515         }
   4516         Preconditions.checkNotNull(who, "ComponentName is null");
   4517         final int userHandle = UserHandle.getCallingUserId();
   4518         synchronized (this) {
   4519             // Check if this is the profile owner who is calling
   4520             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4521             int userId = UserHandle.getCallingUserId();
   4522 
   4523             long id = Binder.clearCallingIdentity();
   4524             try {
   4525                 mUserManager.setUserEnabled(userId);
   4526                 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
   4527                 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle));
   4528                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
   4529                         Intent.FLAG_RECEIVER_FOREGROUND);
   4530                 // TODO This should send to parent of profile (which is always owner at the moment).
   4531                 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
   4532             } finally {
   4533                 restoreCallingIdentity(id);
   4534             }
   4535         }
   4536     }
   4537 
   4538     @Override
   4539     public void setProfileName(ComponentName who, String profileName) {
   4540         Preconditions.checkNotNull(who, "ComponentName is null");
   4541         int userId = UserHandle.getCallingUserId();
   4542         // Check if this is the profile owner (includes device owner).
   4543         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4544 
   4545         long id = Binder.clearCallingIdentity();
   4546         try {
   4547             mUserManager.setUserName(userId, profileName);
   4548         } finally {
   4549             restoreCallingIdentity(id);
   4550         }
   4551     }
   4552 
   4553     @Override
   4554     public ComponentName getProfileOwner(int userHandle) {
   4555         if (!mHasFeature) {
   4556             return null;
   4557         }
   4558 
   4559         synchronized (this) {
   4560             if (mDeviceOwner != null) {
   4561                 return mDeviceOwner.getProfileOwnerComponent(userHandle);
   4562             }
   4563         }
   4564         return null;
   4565     }
   4566 
   4567     // Returns the active profile owner for this user or null if the current user has no
   4568     // profile owner.
   4569     private ActiveAdmin getProfileOwnerAdmin(int userHandle) {
   4570         ComponentName profileOwner =
   4571                 mDeviceOwner != null ? mDeviceOwner.getProfileOwnerComponent(userHandle) : null;
   4572         if (profileOwner == null) {
   4573             return null;
   4574         }
   4575         DevicePolicyData policy = getUserData(userHandle);
   4576         final int n = policy.mAdminList.size();
   4577         for (int i = 0; i < n; i++) {
   4578             ActiveAdmin admin = policy.mAdminList.get(i);
   4579             if (profileOwner.equals(admin.info.getComponent())) {
   4580                 return admin;
   4581             }
   4582         }
   4583         return null;
   4584     }
   4585 
   4586     @Override
   4587     public String getProfileOwnerName(int userHandle) {
   4588         if (!mHasFeature) {
   4589             return null;
   4590         }
   4591         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
   4592         ComponentName profileOwner = getProfileOwner(userHandle);
   4593         if (profileOwner == null) {
   4594             return null;
   4595         }
   4596         return getApplicationLabel(profileOwner.getPackageName(), userHandle);
   4597     }
   4598 
   4599     /**
   4600      * Canonical name for a given package.
   4601      */
   4602     private String getApplicationLabel(String packageName, int userHandle) {
   4603         long token = Binder.clearCallingIdentity();
   4604         try {
   4605             final Context userContext;
   4606             try {
   4607                 UserHandle handle = new UserHandle(userHandle);
   4608                 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
   4609             } catch (PackageManager.NameNotFoundException nnfe) {
   4610                 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
   4611                 return null;
   4612             }
   4613             ApplicationInfo appInfo = userContext.getApplicationInfo();
   4614             CharSequence result = null;
   4615             if (appInfo != null) {
   4616                 PackageManager pm = userContext.getPackageManager();
   4617                 result = pm.getApplicationLabel(appInfo);
   4618             }
   4619             return result != null ? result.toString() : null;
   4620         } finally {
   4621             Binder.restoreCallingIdentity(token);
   4622         }
   4623     }
   4624 
   4625     /**
   4626      * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
   4627      * permission.
   4628      * The profile owner can only be set before the user setup phase has completed,
   4629      * except for:
   4630      * - SYSTEM_UID
   4631      * - adb if there are not accounts.
   4632      */
   4633     private void enforceCanSetProfileOwner(int userHandle) {
   4634         UserInfo info = mUserManager.getUserInfo(userHandle);
   4635         if (info == null) {
   4636             // User doesn't exist.
   4637             throw new IllegalArgumentException(
   4638                     "Attempted to set profile owner for invalid userId: " + userHandle);
   4639         }
   4640         if (info.isGuest()) {
   4641             throw new IllegalStateException("Cannot set a profile owner on a guest");
   4642         }
   4643         if (getProfileOwner(userHandle) != null) {
   4644             throw new IllegalStateException("Trying to set the profile owner, but profile owner "
   4645                     + "is already set.");
   4646         }
   4647         int callingUid = Binder.getCallingUid();
   4648         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
   4649             if (hasUserSetupCompleted(userHandle) &&
   4650                     AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) {
   4651                 throw new IllegalStateException("Not allowed to set the profile owner because "
   4652                         + "there are already some accounts on the profile");
   4653             }
   4654             return;
   4655         }
   4656         mContext.enforceCallingOrSelfPermission(
   4657                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
   4658         if (hasUserSetupCompleted(userHandle)
   4659                 && UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
   4660             throw new IllegalStateException("Cannot set the profile owner on a user which is "
   4661                     + "already set-up");
   4662         }
   4663     }
   4664 
   4665     /**
   4666      * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
   4667      * permission.
   4668      * The device owner can only be set before the setup phase of the primary user has completed,
   4669      * except for adb if no accounts or additional users are present on the device.
   4670      */
   4671     private void enforceCanSetDeviceOwner() {
   4672         if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
   4673             throw new IllegalStateException("Trying to set the device owner, but device owner "
   4674                     + "is already set.");
   4675         }
   4676         int callingUid = Binder.getCallingUid();
   4677         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
   4678             if (!hasUserSetupCompleted(UserHandle.USER_OWNER)) {
   4679                 return;
   4680             }
   4681             if (mUserManager.getUserCount() > 1) {
   4682                 throw new IllegalStateException("Not allowed to set the device owner because there "
   4683                         + "are already several users on the device");
   4684             }
   4685             if (AccountManager.get(mContext).getAccounts().length > 0) {
   4686                 throw new IllegalStateException("Not allowed to set the device owner because there "
   4687                         + "are already some accounts on the device");
   4688             }
   4689             return;
   4690         }
   4691         mContext.enforceCallingOrSelfPermission(
   4692                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
   4693         if (hasUserSetupCompleted(UserHandle.USER_OWNER)) {
   4694             throw new IllegalStateException("Cannot set the device owner if the device is "
   4695                     + "already set-up");
   4696         }
   4697     }
   4698 
   4699     private void enforceCrossUserPermission(int userHandle) {
   4700         if (userHandle < 0) {
   4701             throw new IllegalArgumentException("Invalid userId " + userHandle);
   4702         }
   4703         final int callingUid = Binder.getCallingUid();
   4704         if (userHandle == UserHandle.getUserId(callingUid)) return;
   4705         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
   4706             mContext.enforceCallingOrSelfPermission(
   4707                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have"
   4708                     + " INTERACT_ACROSS_USERS_FULL permission");
   4709         }
   4710     }
   4711 
   4712     private void enforceSystemProcess(String message) {
   4713         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   4714             throw new SecurityException(message);
   4715         }
   4716     }
   4717 
   4718     private void enforceNotManagedProfile(int userHandle, String message) {
   4719         if(isManagedProfile(userHandle)) {
   4720             throw new SecurityException("You can not " + message + " for a managed profile. ");
   4721         }
   4722     }
   4723 
   4724     private UserInfo getProfileParent(int userHandle) {
   4725         long ident = Binder.clearCallingIdentity();
   4726         try {
   4727             return mUserManager.getProfileParent(userHandle);
   4728         } finally {
   4729             Binder.restoreCallingIdentity(ident);
   4730         }
   4731     }
   4732 
   4733     private boolean isManagedProfile(int userHandle) {
   4734         long ident = Binder.clearCallingIdentity();
   4735         try {
   4736             return mUserManager.getUserInfo(userHandle).isManagedProfile();
   4737         } finally {
   4738             Binder.restoreCallingIdentity(ident);
   4739         }
   4740     }
   4741 
   4742     private void enableIfNecessary(String packageName, int userId) {
   4743         try {
   4744             IPackageManager ipm = AppGlobals.getPackageManager();
   4745             ApplicationInfo ai = ipm.getApplicationInfo(packageName,
   4746                     PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
   4747                     userId);
   4748             if (ai.enabledSetting
   4749                     == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
   4750                 ipm.setApplicationEnabledSetting(packageName,
   4751                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
   4752                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
   4753             }
   4754         } catch (RemoteException e) {
   4755         }
   4756     }
   4757 
   4758     @Override
   4759     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   4760         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
   4761                 != PackageManager.PERMISSION_GRANTED) {
   4762 
   4763             pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
   4764                     + Binder.getCallingPid()
   4765                     + ", uid=" + Binder.getCallingUid());
   4766             return;
   4767         }
   4768 
   4769         final Printer p = new PrintWriterPrinter(pw);
   4770 
   4771         synchronized (this) {
   4772             p.println("Current Device Policy Manager state:");
   4773             if (mDeviceOwner != null) {
   4774                 mDeviceOwner.dump("  ", pw);
   4775             }
   4776             int userCount = mUserData.size();
   4777             for (int u = 0; u < userCount; u++) {
   4778                 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
   4779                 p.println("  Enabled Device Admins (User " + policy.mUserHandle + "):");
   4780                 final int N = policy.mAdminList.size();
   4781                 for (int i=0; i<N; i++) {
   4782                     ActiveAdmin ap = policy.mAdminList.get(i);
   4783                     if (ap != null) {
   4784                         pw.print("  "); pw.print(ap.info.getComponent().flattenToShortString());
   4785                                 pw.println(":");
   4786                         ap.dump("    ", pw);
   4787                     }
   4788                 }
   4789                 if (!policy.mRemovingAdmins.isEmpty()) {
   4790                     p.println("  Removing Device Admins (User " + policy.mUserHandle + "): "
   4791                             + policy.mRemovingAdmins);
   4792                 }
   4793 
   4794                 pw.println(" ");
   4795                 pw.print("  mPasswordOwner="); pw.println(policy.mPasswordOwner);
   4796             }
   4797         }
   4798     }
   4799 
   4800     @Override
   4801     public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
   4802             ComponentName activity) {
   4803         Preconditions.checkNotNull(who, "ComponentName is null");
   4804         final int userHandle = UserHandle.getCallingUserId();
   4805         synchronized (this) {
   4806             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4807 
   4808             IPackageManager pm = AppGlobals.getPackageManager();
   4809             long id = Binder.clearCallingIdentity();
   4810             try {
   4811                 pm.addPersistentPreferredActivity(filter, activity, userHandle);
   4812             } catch (RemoteException re) {
   4813                 // Shouldn't happen
   4814             } finally {
   4815                 restoreCallingIdentity(id);
   4816             }
   4817         }
   4818     }
   4819 
   4820     @Override
   4821     public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
   4822         Preconditions.checkNotNull(who, "ComponentName is null");
   4823         final int userHandle = UserHandle.getCallingUserId();
   4824         synchronized (this) {
   4825             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4826 
   4827             IPackageManager pm = AppGlobals.getPackageManager();
   4828             long id = Binder.clearCallingIdentity();
   4829             try {
   4830                 pm.clearPackagePersistentPreferredActivities(packageName, userHandle);
   4831             } catch (RemoteException re) {
   4832                 // Shouldn't happen
   4833             } finally {
   4834                 restoreCallingIdentity(id);
   4835             }
   4836         }
   4837     }
   4838 
   4839     @Override
   4840     public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
   4841         Preconditions.checkNotNull(who, "ComponentName is null");
   4842         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
   4843         synchronized (this) {
   4844             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4845 
   4846             long id = Binder.clearCallingIdentity();
   4847             try {
   4848                 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
   4849             } finally {
   4850                 restoreCallingIdentity(id);
   4851             }
   4852         }
   4853     }
   4854 
   4855     @Override
   4856     public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
   4857             PersistableBundle args) {
   4858         if (!mHasFeature) {
   4859             return;
   4860         }
   4861         Preconditions.checkNotNull(admin, "admin is null");
   4862         Preconditions.checkNotNull(agent, "agent is null");
   4863         final int userHandle = UserHandle.getCallingUserId();
   4864         enforceNotManagedProfile(userHandle, "set trust agent configuration");
   4865         synchronized (this) {
   4866             ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
   4867                     DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
   4868             ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
   4869             saveSettingsLocked(userHandle);
   4870             syncDeviceCapabilitiesLocked(getUserData(userHandle));
   4871         }
   4872     }
   4873 
   4874     @Override
   4875     public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
   4876             ComponentName agent, int userHandle) {
   4877         if (!mHasFeature) {
   4878             return null;
   4879         }
   4880         Preconditions.checkNotNull(agent, "agent null");
   4881         enforceCrossUserPermission(userHandle);
   4882 
   4883         synchronized (this) {
   4884             final String componentName = agent.flattenToString();
   4885             if (admin != null) {
   4886                 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle);
   4887                 if (ap == null) return null;
   4888                 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
   4889                 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
   4890                 List<PersistableBundle> result = new ArrayList<PersistableBundle>();
   4891                 result.add(trustAgentInfo.options);
   4892                 return result;
   4893             }
   4894 
   4895             // Return strictest policy for this user and profiles that are visible from this user.
   4896             final List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
   4897             List<PersistableBundle> result = null;
   4898 
   4899             // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
   4900             // of the options. If any admin doesn't have options, discard options for the rest
   4901             // and return null.
   4902             boolean allAdminsHaveOptions = true;
   4903             for (UserInfo userInfo : profiles) {
   4904                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
   4905                 final int N = policy.mAdminList.size();
   4906                 for (int i=0; i < N; i++) {
   4907                     final ActiveAdmin active = policy.mAdminList.get(i);
   4908                     final boolean disablesTrust = (active.disabledKeyguardFeatures
   4909                             & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
   4910                     final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
   4911                     if (info != null && info.options != null && !info.options.isEmpty()) {
   4912                         if (disablesTrust) {
   4913                             if (result == null) {
   4914                                 result = new ArrayList<PersistableBundle>();
   4915                             }
   4916                             result.add(info.options);
   4917                         } else {
   4918                             Log.w(LOG_TAG, "Ignoring admin " + active.info
   4919                                     + " because it has trust options but doesn't declare "
   4920                                     + "KEYGUARD_DISABLE_TRUST_AGENTS");
   4921                         }
   4922                     } else if (disablesTrust) {
   4923                         allAdminsHaveOptions = false;
   4924                         break;
   4925                     }
   4926                 }
   4927             }
   4928             return allAdminsHaveOptions ? result : null;
   4929         }
   4930     }
   4931 
   4932     @Override
   4933     public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
   4934         Preconditions.checkNotNull(who, "ComponentName is null");
   4935         synchronized (this) {
   4936             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4937 
   4938             int userHandle = UserHandle.getCallingUserId();
   4939             DevicePolicyData userData = getUserData(userHandle);
   4940             userData.mRestrictionsProvider = permissionProvider;
   4941             saveSettingsLocked(userHandle);
   4942         }
   4943     }
   4944 
   4945     @Override
   4946     public ComponentName getRestrictionsProvider(int userHandle) {
   4947         synchronized (this) {
   4948             if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   4949                 throw new SecurityException("Only the system can query the permission provider");
   4950             }
   4951             DevicePolicyData userData = getUserData(userHandle);
   4952             return userData != null ? userData.mRestrictionsProvider : null;
   4953         }
   4954     }
   4955 
   4956     @Override
   4957     public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
   4958         Preconditions.checkNotNull(who, "ComponentName is null");
   4959         int callingUserId = UserHandle.getCallingUserId();
   4960         synchronized (this) {
   4961             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4962 
   4963             IPackageManager pm = AppGlobals.getPackageManager();
   4964             long id = Binder.clearCallingIdentity();
   4965             try {
   4966                 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
   4967                     pm.addCrossProfileIntentFilter(filter, who.getPackageName(), callingUserId,
   4968                             UserHandle.USER_OWNER, 0);
   4969                 }
   4970                 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
   4971                     pm.addCrossProfileIntentFilter(filter, who.getPackageName(),
   4972                             UserHandle.USER_OWNER, callingUserId, 0);
   4973                 }
   4974             } catch (RemoteException re) {
   4975                 // Shouldn't happen
   4976             } finally {
   4977                 restoreCallingIdentity(id);
   4978             }
   4979         }
   4980     }
   4981 
   4982     @Override
   4983     public void clearCrossProfileIntentFilters(ComponentName who) {
   4984         Preconditions.checkNotNull(who, "ComponentName is null");
   4985         int callingUserId = UserHandle.getCallingUserId();
   4986         synchronized (this) {
   4987             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   4988             IPackageManager pm = AppGlobals.getPackageManager();
   4989             long id = Binder.clearCallingIdentity();
   4990             try {
   4991                 // Removing those that go from the managed profile to the primary user.
   4992                 pm.clearCrossProfileIntentFilters(callingUserId, who.getPackageName());
   4993                 // And those that go from the primary user to the managed profile.
   4994                 // If we want to support multiple managed profiles, we will have to only remove
   4995                 // those that have callingUserId as their target.
   4996                 pm.clearCrossProfileIntentFilters(UserHandle.USER_OWNER, who.getPackageName());
   4997             } catch (RemoteException re) {
   4998                 // Shouldn't happen
   4999             } finally {
   5000                 restoreCallingIdentity(id);
   5001             }
   5002         }
   5003     }
   5004 
   5005     /**
   5006      * @return true if all packages in enabledPackages are either in the list
   5007      * permittedList or are a system app.
   5008      */
   5009     private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
   5010             List<String> permittedList) {
   5011         int userIdToCheck = UserHandle.getCallingUserId();
   5012         long id = Binder.clearCallingIdentity();
   5013         try {
   5014             // If we have an enabled packages list for a managed profile the packages
   5015             // we should check are installed for the parent user.
   5016             UserInfo user = mUserManager.getUserInfo(userIdToCheck);
   5017             if (user.isManagedProfile()) {
   5018                 userIdToCheck = user.profileGroupId;
   5019             }
   5020 
   5021             IPackageManager pm = AppGlobals.getPackageManager();
   5022             for (String enabledPackage : enabledPackages) {
   5023                 boolean systemService = false;
   5024                 try {
   5025                     ApplicationInfo applicationInfo = pm.getApplicationInfo(enabledPackage,
   5026                             PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
   5027                     systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
   5028                 } catch (RemoteException e) {
   5029                     Log.i(LOG_TAG, "Can't talk to package managed", e);
   5030                 }
   5031                 if (!systemService && !permittedList.contains(enabledPackage)) {
   5032                     return false;
   5033                 }
   5034             }
   5035         } finally {
   5036             restoreCallingIdentity(id);
   5037         }
   5038         return true;
   5039     }
   5040 
   5041     private AccessibilityManager getAccessibilityManagerForUser(int userId) {
   5042         // Not using AccessibilityManager.getInstance because that guesses
   5043         // at the user you require based on callingUid and caches for a given
   5044         // process.
   5045         IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
   5046         IAccessibilityManager service = iBinder == null
   5047                 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
   5048         return new AccessibilityManager(mContext, service, userId);
   5049     }
   5050 
   5051     @Override
   5052     public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
   5053         if (!mHasFeature) {
   5054             return false;
   5055         }
   5056         Preconditions.checkNotNull(who, "ComponentName is null");
   5057 
   5058         if (packageList != null) {
   5059             int userId = UserHandle.getCallingUserId();
   5060             List<AccessibilityServiceInfo> enabledServices = null;
   5061             long id = Binder.clearCallingIdentity();
   5062             try {
   5063                 UserInfo user = mUserManager.getUserInfo(userId);
   5064                 if (user.isManagedProfile()) {
   5065                     userId = user.profileGroupId;
   5066                 }
   5067                 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
   5068                 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
   5069                         AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
   5070             } finally {
   5071                 restoreCallingIdentity(id);
   5072             }
   5073 
   5074             if (enabledServices != null) {
   5075                 List<String> enabledPackages = new ArrayList<String>();
   5076                 for (AccessibilityServiceInfo service : enabledServices) {
   5077                     enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
   5078                 }
   5079                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
   5080                     Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
   5081                             + "because it contains already enabled accesibility services.");
   5082                     return false;
   5083                 }
   5084             }
   5085         }
   5086 
   5087         synchronized (this) {
   5088             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   5089                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5090             admin.permittedAccessiblityServices = packageList;
   5091             saveSettingsLocked(UserHandle.getCallingUserId());
   5092         }
   5093         return true;
   5094     }
   5095 
   5096     @Override
   5097     public List getPermittedAccessibilityServices(ComponentName who) {
   5098         if (!mHasFeature) {
   5099             return null;
   5100         }
   5101         Preconditions.checkNotNull(who, "ComponentName is null");
   5102 
   5103         synchronized (this) {
   5104             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   5105                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5106             return admin.permittedAccessiblityServices;
   5107         }
   5108     }
   5109 
   5110     @Override
   5111     public List getPermittedAccessibilityServicesForUser(int userId) {
   5112         if (!mHasFeature) {
   5113             return null;
   5114         }
   5115         synchronized (this) {
   5116             List<String> result = null;
   5117             // If we have multiple profiles we return the intersection of the
   5118             // permitted lists. This can happen in cases where we have a device
   5119             // and profile owner.
   5120             List<UserInfo> profiles = mUserManager.getProfiles(userId);
   5121             final int PROFILES_SIZE = profiles.size();
   5122             for (int i = 0; i < PROFILES_SIZE; ++i) {
   5123                 // Just loop though all admins, only device or profiles
   5124                 // owners can have permitted lists set.
   5125                 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
   5126                 final int N = policy.mAdminList.size();
   5127                 for (int j = 0; j < N; j++) {
   5128                     ActiveAdmin admin = policy.mAdminList.get(j);
   5129                     List<String> fromAdmin = admin.permittedAccessiblityServices;
   5130                     if (fromAdmin != null) {
   5131                         if (result == null) {
   5132                             result = new ArrayList<String>(fromAdmin);
   5133                         } else {
   5134                             result.retainAll(fromAdmin);
   5135                         }
   5136                     }
   5137                 }
   5138             }
   5139 
   5140             // If we have a permitted list add all system accessibility services.
   5141             if (result != null) {
   5142                 long id = Binder.clearCallingIdentity();
   5143                 try {
   5144                     UserInfo user = mUserManager.getUserInfo(userId);
   5145                     if (user.isManagedProfile()) {
   5146                         userId = user.profileGroupId;
   5147                     }
   5148                     AccessibilityManager accessibilityManager =
   5149                             getAccessibilityManagerForUser(userId);
   5150                     List<AccessibilityServiceInfo> installedServices =
   5151                             accessibilityManager.getInstalledAccessibilityServiceList();
   5152 
   5153                     IPackageManager pm = AppGlobals.getPackageManager();
   5154                     if (installedServices != null) {
   5155                         for (AccessibilityServiceInfo service : installedServices) {
   5156                             ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
   5157                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
   5158                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
   5159                                 result.add(serviceInfo.packageName);
   5160                             }
   5161                         }
   5162                     }
   5163                 } finally {
   5164                     restoreCallingIdentity(id);
   5165                 }
   5166             }
   5167 
   5168             return result;
   5169         }
   5170     }
   5171 
   5172     private boolean checkCallerIsCurrentUserOrProfile() {
   5173         int callingUserId = UserHandle.getCallingUserId();
   5174         long token = Binder.clearCallingIdentity();
   5175         try {
   5176             UserInfo currentUser;
   5177             UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
   5178             try {
   5179                 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
   5180             } catch (RemoteException e) {
   5181                 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
   5182                 return false;
   5183             }
   5184 
   5185             if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
   5186                 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
   5187                         + "of a user that isn't the foreground user.");
   5188                 return false;
   5189             }
   5190             if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
   5191                 Slog.e(LOG_TAG, "Cannot set permitted input methods "
   5192                         + "of a user that isn't the foreground user.");
   5193                 return false;
   5194             }
   5195         } finally {
   5196             Binder.restoreCallingIdentity(token);
   5197         }
   5198         return true;
   5199     }
   5200 
   5201     @Override
   5202     public boolean setPermittedInputMethods(ComponentName who, List packageList) {
   5203         if (!mHasFeature) {
   5204             return false;
   5205         }
   5206         Preconditions.checkNotNull(who, "ComponentName is null");
   5207 
   5208         // TODO When InputMethodManager supports per user calls remove
   5209         //      this restriction.
   5210         if (!checkCallerIsCurrentUserOrProfile()) {
   5211             return false;
   5212         }
   5213 
   5214         if (packageList != null) {
   5215             // InputMethodManager fetches input methods for current user.
   5216             // So this can only be set when calling user is the current user
   5217             // or parent is current user in case of managed profiles.
   5218             InputMethodManager inputMethodManager = (InputMethodManager) mContext
   5219                     .getSystemService(Context.INPUT_METHOD_SERVICE);
   5220             List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
   5221 
   5222             if (enabledImes != null) {
   5223                 List<String> enabledPackages = new ArrayList<String>();
   5224                 for (InputMethodInfo ime : enabledImes) {
   5225                     enabledPackages.add(ime.getPackageName());
   5226                 }
   5227                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
   5228                     Slog.e(LOG_TAG, "Cannot set permitted input methods, "
   5229                             + "because it contains already enabled input method.");
   5230                     return false;
   5231                 }
   5232             }
   5233         }
   5234 
   5235         synchronized (this) {
   5236             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   5237                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5238             admin.permittedInputMethods = packageList;
   5239             saveSettingsLocked(UserHandle.getCallingUserId());
   5240         }
   5241         return true;
   5242     }
   5243 
   5244     @Override
   5245     public List getPermittedInputMethods(ComponentName who) {
   5246         if (!mHasFeature) {
   5247             return null;
   5248         }
   5249         Preconditions.checkNotNull(who, "ComponentName is null");
   5250 
   5251         synchronized (this) {
   5252             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   5253                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5254             return admin.permittedInputMethods;
   5255         }
   5256     }
   5257 
   5258     @Override
   5259     public List getPermittedInputMethodsForCurrentUser() {
   5260         UserInfo currentUser;
   5261         try {
   5262             currentUser = ActivityManagerNative.getDefault().getCurrentUser();
   5263         } catch (RemoteException e) {
   5264             Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
   5265             // Activity managed is dead, just allow all IMEs
   5266             return null;
   5267         }
   5268 
   5269         int userId = currentUser.id;
   5270         synchronized (this) {
   5271             List<String> result = null;
   5272             // If we have multiple profiles we return the intersection of the
   5273             // permitted lists. This can happen in cases where we have a device
   5274             // and profile owner.
   5275             List<UserInfo> profiles = mUserManager.getProfiles(userId);
   5276             final int PROFILES_SIZE = profiles.size();
   5277             for (int i = 0; i < PROFILES_SIZE; ++i) {
   5278                 // Just loop though all admins, only device or profiles
   5279                 // owners can have permitted lists set.
   5280                 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
   5281                 final int N = policy.mAdminList.size();
   5282                 for (int j = 0; j < N; j++) {
   5283                     ActiveAdmin admin = policy.mAdminList.get(j);
   5284                     List<String> fromAdmin = admin.permittedInputMethods;
   5285                     if (fromAdmin != null) {
   5286                         if (result == null) {
   5287                             result = new ArrayList<String>(fromAdmin);
   5288                         } else {
   5289                             result.retainAll(fromAdmin);
   5290                         }
   5291                     }
   5292                 }
   5293             }
   5294 
   5295             // If we have a permitted list add all system input methods.
   5296             if (result != null) {
   5297                 InputMethodManager inputMethodManager = (InputMethodManager) mContext
   5298                         .getSystemService(Context.INPUT_METHOD_SERVICE);
   5299                 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
   5300                 long id = Binder.clearCallingIdentity();
   5301                 try {
   5302                     IPackageManager pm = AppGlobals.getPackageManager();
   5303                     if (imes != null) {
   5304                         for (InputMethodInfo ime : imes) {
   5305                             ServiceInfo serviceInfo = ime.getServiceInfo();
   5306                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
   5307                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
   5308                                 result.add(serviceInfo.packageName);
   5309                             }
   5310                         }
   5311                     }
   5312                 } finally {
   5313                     restoreCallingIdentity(id);
   5314                 }
   5315             }
   5316             return result;
   5317         }
   5318     }
   5319 
   5320     @Override
   5321     public UserHandle createUser(ComponentName who, String name) {
   5322         Preconditions.checkNotNull(who, "ComponentName is null");
   5323         synchronized (this) {
   5324             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5325 
   5326             long id = Binder.clearCallingIdentity();
   5327             try {
   5328                 UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */);
   5329                 if (userInfo != null) {
   5330                     return userInfo.getUserHandle();
   5331                 }
   5332                 return null;
   5333             } finally {
   5334                 restoreCallingIdentity(id);
   5335             }
   5336         }
   5337     }
   5338 
   5339     @Override
   5340     public UserHandle createAndInitializeUser(ComponentName who, String name,
   5341             String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) {
   5342         UserHandle user = createUser(who, name);
   5343         if (user == null) {
   5344             return null;
   5345         }
   5346         long id = Binder.clearCallingIdentity();
   5347         try {
   5348             String profileOwnerPkg = profileOwnerComponent.getPackageName();
   5349             final IPackageManager ipm = AppGlobals.getPackageManager();
   5350             IActivityManager activityManager = ActivityManagerNative.getDefault();
   5351 
   5352             final int userHandle = user.getIdentifier();
   5353             try {
   5354                 // Install the profile owner if not present.
   5355                 if (!ipm.isPackageAvailable(profileOwnerPkg, userHandle)) {
   5356                     ipm.installExistingPackageAsUser(profileOwnerPkg, userHandle);
   5357                 }
   5358 
   5359                 // Start user in background.
   5360                 activityManager.startUserInBackground(userHandle);
   5361             } catch (RemoteException e) {
   5362                 Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e);
   5363             }
   5364 
   5365             setActiveAdmin(profileOwnerComponent, true, userHandle, adminExtras);
   5366             setProfileOwner(profileOwnerComponent, ownerName, userHandle);
   5367             return user;
   5368         } finally {
   5369             restoreCallingIdentity(id);
   5370         }
   5371     }
   5372 
   5373     @Override
   5374     public boolean removeUser(ComponentName who, UserHandle userHandle) {
   5375         Preconditions.checkNotNull(who, "ComponentName is null");
   5376         synchronized (this) {
   5377             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5378 
   5379             long id = Binder.clearCallingIdentity();
   5380             try {
   5381                 return mUserManager.removeUser(userHandle.getIdentifier());
   5382             } finally {
   5383                 restoreCallingIdentity(id);
   5384             }
   5385         }
   5386     }
   5387 
   5388     @Override
   5389     public boolean switchUser(ComponentName who, UserHandle userHandle) {
   5390         Preconditions.checkNotNull(who, "ComponentName is null");
   5391         synchronized (this) {
   5392             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5393 
   5394             long id = Binder.clearCallingIdentity();
   5395             try {
   5396                 int userId = UserHandle.USER_OWNER;
   5397                 if (userHandle != null) {
   5398                     userId = userHandle.getIdentifier();
   5399                 }
   5400                 return ActivityManagerNative.getDefault().switchUser(userId);
   5401             } catch (RemoteException e) {
   5402                 Log.e(LOG_TAG, "Couldn't switch user", e);
   5403                 return false;
   5404             } finally {
   5405                 restoreCallingIdentity(id);
   5406             }
   5407         }
   5408     }
   5409 
   5410     @Override
   5411     public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
   5412         Preconditions.checkNotNull(who, "ComponentName is null");
   5413         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
   5414 
   5415         synchronized (this) {
   5416             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5417 
   5418             long id = Binder.clearCallingIdentity();
   5419             try {
   5420                 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
   5421                 // if no restrictions were saved, mUserManager.getApplicationRestrictions
   5422                 // returns null, but DPM method should return an empty Bundle as per JavaDoc
   5423                 return bundle != null ? bundle : Bundle.EMPTY;
   5424             } finally {
   5425                 restoreCallingIdentity(id);
   5426             }
   5427         }
   5428     }
   5429 
   5430     @Override
   5431     public void setUserRestriction(ComponentName who, String key, boolean enabled) {
   5432         Preconditions.checkNotNull(who, "ComponentName is null");
   5433         final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
   5434         final int userHandle = user.getIdentifier();
   5435         synchronized (this) {
   5436             ActiveAdmin activeAdmin =
   5437                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5438             boolean isDeviceOwner = isDeviceOwner(activeAdmin.info.getPackageName());
   5439             if (!isDeviceOwner && userHandle != UserHandle.USER_OWNER
   5440                     && DEVICE_OWNER_USER_RESTRICTIONS.contains(key)) {
   5441                 throw new SecurityException("Profile owners cannot set user restriction " + key);
   5442             }
   5443             if (IMMUTABLE_USER_RESTRICTIONS.contains(key)) {
   5444                 throw new SecurityException("User restriction " + key + " cannot be changed");
   5445             }
   5446             boolean alreadyRestricted = mUserManager.hasUserRestriction(key, user);
   5447 
   5448             IAudioService iAudioService = null;
   5449             if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)
   5450                     || UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
   5451                 iAudioService = IAudioService.Stub.asInterface(
   5452                         ServiceManager.getService(Context.AUDIO_SERVICE));
   5453             }
   5454 
   5455             long id = Binder.clearCallingIdentity();
   5456             try {
   5457                 if (enabled && !alreadyRestricted) {
   5458                     if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
   5459                         iAudioService.setMicrophoneMute(true, mContext.getPackageName(),
   5460                                 userHandle);
   5461                     } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
   5462                         iAudioService.setMasterMute(true, 0, mContext.getPackageName(),
   5463                                 userHandle);
   5464                     }
   5465                     if (UserManager.DISALLOW_CONFIG_WIFI.equals(key)) {
   5466                         Settings.Secure.putIntForUser(mContext.getContentResolver(),
   5467                                 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0,
   5468                                 userHandle);
   5469                     } else if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
   5470                         Settings.Secure.putIntForUser(mContext.getContentResolver(),
   5471                                 Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF,
   5472                                 userHandle);
   5473                         Settings.Secure.putStringForUser(mContext.getContentResolver(),
   5474                                 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, "",
   5475                                 userHandle);
   5476                     } else if (UserManager.DISALLOW_DEBUGGING_FEATURES.equals(key)) {
   5477                         // Only disable adb if changing for primary user, since it is global
   5478                         if (userHandle == UserHandle.USER_OWNER) {
   5479                             Settings.Global.putStringForUser(mContext.getContentResolver(),
   5480                                     Settings.Global.ADB_ENABLED, "0", userHandle);
   5481                         }
   5482                     } else if (UserManager.ENSURE_VERIFY_APPS.equals(key)) {
   5483                         Settings.Global.putStringForUser(mContext.getContentResolver(),
   5484                                 Settings.Global.PACKAGE_VERIFIER_ENABLE, "1",
   5485                                 userHandle);
   5486                         Settings.Global.putStringForUser(mContext.getContentResolver(),
   5487                                 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1",
   5488                                 userHandle);
   5489                     } else if (UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES.equals(key)) {
   5490                         Settings.Secure.putIntForUser(mContext.getContentResolver(),
   5491                                 Settings.Secure.INSTALL_NON_MARKET_APPS, 0,
   5492                                 userHandle);
   5493                     }
   5494                 }
   5495                 mUserManager.setUserRestriction(key, enabled, user);
   5496                 if (enabled != alreadyRestricted) {
   5497                     if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
   5498                         // Send out notifications however as some clients may want to reread the
   5499                         // value which actually changed due to a restriction having been applied.
   5500                         final String property = Settings.Secure.SYS_PROP_SETTING_VERSION;
   5501                         long version = SystemProperties.getLong(property, 0) + 1;
   5502                         SystemProperties.set(property, Long.toString(version));
   5503 
   5504                         final String name = Settings.Secure.LOCATION_PROVIDERS_ALLOWED;
   5505                         Uri url = Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
   5506                         mContext.getContentResolver().notifyChange(url, null, true, userHandle);
   5507                     }
   5508                 }
   5509                 if (!enabled && alreadyRestricted) {
   5510                     if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
   5511                         iAudioService.setMicrophoneMute(false, mContext.getPackageName(),
   5512                                 userHandle);
   5513                     } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
   5514                         iAudioService.setMasterMute(false, 0, mContext.getPackageName(),
   5515                                 userHandle);
   5516                     }
   5517                 }
   5518             } catch (RemoteException re) {
   5519                 Slog.e(LOG_TAG, "Failed to talk to AudioService.", re);
   5520             } finally {
   5521                 restoreCallingIdentity(id);
   5522             }
   5523             sendChangedNotification(userHandle);
   5524         }
   5525     }
   5526 
   5527     @Override
   5528     public boolean setApplicationHidden(ComponentName who, String packageName,
   5529             boolean hidden) {
   5530         Preconditions.checkNotNull(who, "ComponentName is null");
   5531         int callingUserId = UserHandle.getCallingUserId();
   5532         synchronized (this) {
   5533             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5534 
   5535             long id = Binder.clearCallingIdentity();
   5536             try {
   5537                 IPackageManager pm = AppGlobals.getPackageManager();
   5538                 return pm.setApplicationHiddenSettingAsUser(packageName, hidden, callingUserId);
   5539             } catch (RemoteException re) {
   5540                 // shouldn't happen
   5541                 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
   5542             } finally {
   5543                 restoreCallingIdentity(id);
   5544             }
   5545             return false;
   5546         }
   5547     }
   5548 
   5549     @Override
   5550     public boolean isApplicationHidden(ComponentName who, String packageName) {
   5551         Preconditions.checkNotNull(who, "ComponentName is null");
   5552         int callingUserId = UserHandle.getCallingUserId();
   5553         synchronized (this) {
   5554             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5555 
   5556             long id = Binder.clearCallingIdentity();
   5557             try {
   5558                 IPackageManager pm = AppGlobals.getPackageManager();
   5559                 return pm.getApplicationHiddenSettingAsUser(packageName, callingUserId);
   5560             } catch (RemoteException re) {
   5561                 // shouldn't happen
   5562                 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
   5563             } finally {
   5564                 restoreCallingIdentity(id);
   5565             }
   5566             return false;
   5567         }
   5568     }
   5569 
   5570     @Override
   5571     public void enableSystemApp(ComponentName who, String packageName) {
   5572         Preconditions.checkNotNull(who, "ComponentName is null");
   5573         synchronized (this) {
   5574             // This API can only be called by an active device admin,
   5575             // so try to retrieve it to check that the caller is one.
   5576             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5577 
   5578             int userId = UserHandle.getCallingUserId();
   5579             long id = Binder.clearCallingIdentity();
   5580 
   5581             try {
   5582                 if (DBG) {
   5583                     Slog.v(LOG_TAG, "installing " + packageName + " for "
   5584                             + userId);
   5585                 }
   5586 
   5587                 UserManager um = UserManager.get(mContext);
   5588                 UserInfo primaryUser = um.getProfileParent(userId);
   5589 
   5590                 // Call did not come from a managed profile
   5591                 if (primaryUser == null) {
   5592                     primaryUser = um.getUserInfo(userId);
   5593                 }
   5594 
   5595                 IPackageManager pm = AppGlobals.getPackageManager();
   5596                 if (!isSystemApp(pm, packageName, primaryUser.id)) {
   5597                     throw new IllegalArgumentException("Only system apps can be enabled this way.");
   5598                 }
   5599 
   5600                 // Install the app.
   5601                 pm.installExistingPackageAsUser(packageName, userId);
   5602 
   5603             } catch (RemoteException re) {
   5604                 // shouldn't happen
   5605                 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
   5606             } finally {
   5607                 restoreCallingIdentity(id);
   5608             }
   5609         }
   5610     }
   5611 
   5612     @Override
   5613     public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
   5614         Preconditions.checkNotNull(who, "ComponentName is null");
   5615         synchronized (this) {
   5616             // This API can only be called by an active device admin,
   5617             // so try to retrieve it to check that the caller is one.
   5618             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5619 
   5620             int userId = UserHandle.getCallingUserId();
   5621             long id = Binder.clearCallingIdentity();
   5622 
   5623             try {
   5624                 UserManager um = UserManager.get(mContext);
   5625                 UserInfo primaryUser = um.getProfileParent(userId);
   5626 
   5627                 // Call did not come from a managed profile.
   5628                 if (primaryUser == null) {
   5629                     primaryUser = um.getUserInfo(userId);
   5630                 }
   5631 
   5632                 IPackageManager pm = AppGlobals.getPackageManager();
   5633                 List<ResolveInfo> activitiesToEnable = pm.queryIntentActivities(intent,
   5634                         intent.resolveTypeIfNeeded(mContext.getContentResolver()),
   5635                         0, // no flags
   5636                         primaryUser.id);
   5637 
   5638                 if (DBG) Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
   5639                 int numberOfAppsInstalled = 0;
   5640                 if (activitiesToEnable != null) {
   5641                     for (ResolveInfo info : activitiesToEnable) {
   5642                         if (info.activityInfo != null) {
   5643                             String packageName = info.activityInfo.packageName;
   5644                             if (isSystemApp(pm, packageName, primaryUser.id)) {
   5645                                 numberOfAppsInstalled++;
   5646                                 pm.installExistingPackageAsUser(packageName, userId);
   5647                             } else {
   5648                                 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
   5649                                         + " system app");
   5650                             }
   5651                         }
   5652                     }
   5653                 }
   5654                 return numberOfAppsInstalled;
   5655             } catch (RemoteException e) {
   5656                 // shouldn't happen
   5657                 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
   5658                 return 0;
   5659             } finally {
   5660                 restoreCallingIdentity(id);
   5661             }
   5662         }
   5663     }
   5664 
   5665     private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
   5666             throws RemoteException {
   5667         ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
   5668                 userId);
   5669         if (appInfo == null) {
   5670             throw new IllegalArgumentException("The application " + packageName +
   5671                     " is not present on this device");
   5672         }
   5673         return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
   5674     }
   5675 
   5676     @Override
   5677     public void setAccountManagementDisabled(ComponentName who, String accountType,
   5678             boolean disabled) {
   5679         if (!mHasFeature) {
   5680             return;
   5681         }
   5682         Preconditions.checkNotNull(who, "ComponentName is null");
   5683         synchronized (this) {
   5684             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
   5685                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5686             if (disabled) {
   5687                 ap.accountTypesWithManagementDisabled.add(accountType);
   5688             } else {
   5689                 ap.accountTypesWithManagementDisabled.remove(accountType);
   5690             }
   5691             saveSettingsLocked(UserHandle.getCallingUserId());
   5692         }
   5693     }
   5694 
   5695     @Override
   5696     public String[] getAccountTypesWithManagementDisabled() {
   5697         return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
   5698     }
   5699 
   5700     @Override
   5701     public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
   5702         enforceCrossUserPermission(userId);
   5703         if (!mHasFeature) {
   5704             return null;
   5705         }
   5706         synchronized (this) {
   5707             DevicePolicyData policy = getUserData(userId);
   5708             final int N = policy.mAdminList.size();
   5709             HashSet<String> resultSet = new HashSet<String>();
   5710             for (int i = 0; i < N; i++) {
   5711                 ActiveAdmin admin = policy.mAdminList.get(i);
   5712                 resultSet.addAll(admin.accountTypesWithManagementDisabled);
   5713             }
   5714             return resultSet.toArray(new String[resultSet.size()]);
   5715         }
   5716     }
   5717 
   5718     @Override
   5719     public void setUninstallBlocked(ComponentName who, String packageName,
   5720             boolean uninstallBlocked) {
   5721         Preconditions.checkNotNull(who, "ComponentName is null");
   5722         final int userId = UserHandle.getCallingUserId();
   5723         synchronized (this) {
   5724             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5725 
   5726             long id = Binder.clearCallingIdentity();
   5727             try {
   5728                 IPackageManager pm = AppGlobals.getPackageManager();
   5729                 pm.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
   5730             } catch (RemoteException re) {
   5731                 // Shouldn't happen.
   5732                 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
   5733             } finally {
   5734                 restoreCallingIdentity(id);
   5735             }
   5736         }
   5737     }
   5738 
   5739     @Override
   5740     public boolean isUninstallBlocked(ComponentName who, String packageName) {
   5741         // This function should return true if and only if the package is blocked by
   5742         // setUninstallBlocked(). It should still return false for other cases of blocks, such as
   5743         // when the package is a system app, or when it is an active device admin.
   5744         final int userId = UserHandle.getCallingUserId();
   5745 
   5746         synchronized (this) {
   5747             if (who != null) {
   5748                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5749             }
   5750 
   5751             long id = Binder.clearCallingIdentity();
   5752             try {
   5753                 IPackageManager pm = AppGlobals.getPackageManager();
   5754                 return pm.getBlockUninstallForUser(packageName, userId);
   5755             } catch (RemoteException re) {
   5756                 // Shouldn't happen.
   5757                 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
   5758             } finally {
   5759                 restoreCallingIdentity(id);
   5760             }
   5761         }
   5762         return false;
   5763     }
   5764 
   5765     @Override
   5766     public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
   5767         if (!mHasFeature) {
   5768             return;
   5769         }
   5770         Preconditions.checkNotNull(who, "ComponentName is null");
   5771         synchronized (this) {
   5772             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   5773                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5774             if (admin.disableCallerId != disabled) {
   5775                 admin.disableCallerId = disabled;
   5776                 saveSettingsLocked(UserHandle.getCallingUserId());
   5777             }
   5778         }
   5779     }
   5780 
   5781     @Override
   5782     public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
   5783         if (!mHasFeature) {
   5784             return false;
   5785         }
   5786         Preconditions.checkNotNull(who, "ComponentName is null");
   5787         synchronized (this) {
   5788             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   5789                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5790             return admin.disableCallerId;
   5791         }
   5792     }
   5793 
   5794     @Override
   5795     public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
   5796         // TODO: Should there be a check to make sure this relationship is within a profile group?
   5797         //enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
   5798         synchronized (this) {
   5799             ActiveAdmin admin = getProfileOwnerAdmin(userId);
   5800             return (admin != null) ? admin.disableCallerId : false;
   5801         }
   5802     }
   5803 
   5804     @Override
   5805     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
   5806             Intent originalIntent) {
   5807         final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(
   5808                 actualLookupKey, actualContactId, originalIntent);
   5809         final int callingUserId = UserHandle.getCallingUserId();
   5810 
   5811         final long ident = Binder.clearCallingIdentity();
   5812         try {
   5813             synchronized (this) {
   5814                 final int managedUserId = getManagedUserId(callingUserId);
   5815                 if (managedUserId < 0) {
   5816                     return;
   5817                 }
   5818                 if (getCrossProfileCallerIdDisabledForUser(managedUserId)) {
   5819                     if (VERBOSE_LOG) {
   5820                         Log.v(LOG_TAG,
   5821                                 "Cross-profile contacts access disabled for user " + managedUserId);
   5822                     }
   5823                     return;
   5824                 }
   5825                 ContactsInternal.startQuickContactWithErrorToastForUser(
   5826                         mContext, intent, new UserHandle(managedUserId));
   5827             }
   5828         } finally {
   5829             Binder.restoreCallingIdentity(ident);
   5830         }
   5831     }
   5832 
   5833     /**
   5834      * @return the user ID of the managed user that is linked to the current user, if any.
   5835      * Otherwise -1.
   5836      */
   5837     public int getManagedUserId(int callingUserId) {
   5838         if (VERBOSE_LOG) {
   5839             Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
   5840         }
   5841 
   5842         for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
   5843             if (ui.id == callingUserId || !ui.isManagedProfile()) {
   5844                 continue; // Caller user self, or not a managed profile.  Skip.
   5845             }
   5846             if (VERBOSE_LOG) {
   5847                 Log.v(LOG_TAG, "Managed user=" + ui.id);
   5848             }
   5849             return ui.id;
   5850         }
   5851         if (VERBOSE_LOG) {
   5852             Log.v(LOG_TAG, "Managed user not found.");
   5853         }
   5854         return -1;
   5855     }
   5856 
   5857     @Override
   5858     public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
   5859         if (!mHasFeature) {
   5860             return;
   5861         }
   5862         Preconditions.checkNotNull(who, "ComponentName is null");
   5863         synchronized (this) {
   5864             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   5865                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5866             if (admin.disableBluetoothContactSharing != disabled) {
   5867                 admin.disableBluetoothContactSharing = disabled;
   5868                 saveSettingsLocked(UserHandle.getCallingUserId());
   5869             }
   5870         }
   5871     }
   5872 
   5873     @Override
   5874     public boolean getBluetoothContactSharingDisabled(ComponentName who) {
   5875         if (!mHasFeature) {
   5876             return false;
   5877         }
   5878         Preconditions.checkNotNull(who, "ComponentName is null");
   5879         synchronized (this) {
   5880             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
   5881                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   5882             return admin.disableBluetoothContactSharing;
   5883         }
   5884     }
   5885 
   5886     @Override
   5887     public boolean getBluetoothContactSharingDisabledForUser(int userId) {
   5888         // TODO: Should there be a check to make sure this relationship is
   5889         // within a profile group?
   5890         // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
   5891         synchronized (this) {
   5892             ActiveAdmin admin = getProfileOwnerAdmin(userId);
   5893             return (admin != null) ? admin.disableBluetoothContactSharing : false;
   5894         }
   5895     }
   5896 
   5897     /**
   5898      * Sets which packages may enter lock task mode.
   5899      *
   5900      * This function can only be called by the device owner.
   5901      * @param packages The list of packages allowed to enter lock task mode.
   5902      */
   5903     @Override
   5904     public void setLockTaskPackages(ComponentName who, String[] packages)
   5905             throws SecurityException {
   5906         Preconditions.checkNotNull(who, "ComponentName is null");
   5907         synchronized (this) {
   5908             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5909 
   5910             int userHandle = Binder.getCallingUserHandle().getIdentifier();
   5911             setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
   5912         }
   5913     }
   5914 
   5915     private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
   5916         DevicePolicyData policy = getUserData(userHandle);
   5917         policy.mLockTaskPackages = packages;
   5918 
   5919         // Store the settings persistently.
   5920         saveSettingsLocked(userHandle);
   5921         updateLockTaskPackagesLocked(packages, userHandle);
   5922     }
   5923 
   5924     /**
   5925      * This function returns the list of components allowed to start the task lock mode.
   5926      */
   5927     @Override
   5928     public String[] getLockTaskPackages(ComponentName who) {
   5929         Preconditions.checkNotNull(who, "ComponentName is null");
   5930         synchronized (this) {
   5931             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   5932             int userHandle = Binder.getCallingUserHandle().getIdentifier();
   5933             final List<String> packages = getLockTaskPackagesLocked(userHandle);
   5934             return packages.toArray(new String[packages.size()]);
   5935         }
   5936     }
   5937 
   5938     private List<String> getLockTaskPackagesLocked(int userHandle) {
   5939         final DevicePolicyData policy = getUserData(userHandle);
   5940         return policy.mLockTaskPackages;
   5941     }
   5942 
   5943     /**
   5944      * This function lets the caller know whether the given package is allowed to start the
   5945      * lock task mode.
   5946      * @param pkg The package to check
   5947      */
   5948     @Override
   5949     public boolean isLockTaskPermitted(String pkg) {
   5950         // Get current user's devicepolicy
   5951         int uid = Binder.getCallingUid();
   5952         int userHandle = UserHandle.getUserId(uid);
   5953         DevicePolicyData policy = getUserData(userHandle);
   5954         synchronized (this) {
   5955             for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
   5956                 String lockTaskPackage = policy.mLockTaskPackages.get(i);
   5957 
   5958                 // If the given package equals one of the packages stored our list,
   5959                 // we allow this package to start lock task mode.
   5960                 if (lockTaskPackage.equals(pkg)) {
   5961                     return true;
   5962                 }
   5963             }
   5964         }
   5965         return false;
   5966     }
   5967 
   5968     @Override
   5969     public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
   5970         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   5971             throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
   5972         }
   5973         synchronized (this) {
   5974             final DevicePolicyData policy = getUserData(userHandle);
   5975             Bundle adminExtras = new Bundle();
   5976             adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
   5977             for (ActiveAdmin admin : policy.mAdminList) {
   5978                 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
   5979                 boolean ownsProfile = (getProfileOwner(userHandle) != null
   5980                         && getProfileOwner(userHandle).equals(admin.info.getPackageName()));
   5981                 if (ownsDevice || ownsProfile) {
   5982                     if (isEnabled) {
   5983                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
   5984                                 adminExtras, null);
   5985                     } else {
   5986                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
   5987                     }
   5988                 }
   5989             }
   5990         }
   5991     }
   5992 
   5993     @Override
   5994     public void setGlobalSetting(ComponentName who, String setting, String value) {
   5995         final ContentResolver contentResolver = mContext.getContentResolver();
   5996         Preconditions.checkNotNull(who, "ComponentName is null");
   5997 
   5998         synchronized (this) {
   5999             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   6000 
   6001             // Some settings are no supported any more. However we do not want to throw a
   6002             // SecurityException to avoid breaking apps.
   6003             if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
   6004                 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
   6005                 return;
   6006             }
   6007 
   6008             if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
   6009                 throw new SecurityException(String.format(
   6010                         "Permission denial: device owners cannot update %1$s", setting));
   6011             }
   6012 
   6013             if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
   6014                 // ignore if it contradicts an existing policy
   6015                 long timeMs = getMaximumTimeToLock(who, UserHandle.getCallingUserId());
   6016                 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
   6017                     return;
   6018                 }
   6019             }
   6020 
   6021             long id = Binder.clearCallingIdentity();
   6022             try {
   6023                 Settings.Global.putString(contentResolver, setting, value);
   6024             } finally {
   6025                 restoreCallingIdentity(id);
   6026             }
   6027         }
   6028     }
   6029 
   6030     @Override
   6031     public void setSecureSetting(ComponentName who, String setting, String value) {
   6032         Preconditions.checkNotNull(who, "ComponentName is null");
   6033         int callingUserId = UserHandle.getCallingUserId();
   6034         final ContentResolver contentResolver = mContext.getContentResolver();
   6035 
   6036         synchronized (this) {
   6037             ActiveAdmin activeAdmin =
   6038                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6039 
   6040             if (isDeviceOwner(activeAdmin.info.getPackageName())) {
   6041                 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
   6042                     throw new SecurityException(String.format(
   6043                             "Permission denial: Device owners cannot update %1$s", setting));
   6044                 }
   6045             } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
   6046                 throw new SecurityException(String.format(
   6047                         "Permission denial: Profile owners cannot update %1$s", setting));
   6048             }
   6049 
   6050             long id = Binder.clearCallingIdentity();
   6051             try {
   6052                 Settings.Secure.putStringForUser(contentResolver, setting, value, callingUserId);
   6053             } finally {
   6054                 restoreCallingIdentity(id);
   6055             }
   6056         }
   6057     }
   6058 
   6059     @Override
   6060     public void setMasterVolumeMuted(ComponentName who, boolean on) {
   6061         Preconditions.checkNotNull(who, "ComponentName is null");
   6062         synchronized (this) {
   6063             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6064             int userId = UserHandle.getCallingUserId();
   6065             long identity = Binder.clearCallingIdentity();
   6066             try {
   6067                 IAudioService iAudioService = IAudioService.Stub.asInterface(
   6068                         ServiceManager.getService(Context.AUDIO_SERVICE));
   6069                 iAudioService.setMasterMute(on, 0, mContext.getPackageName(), userId);
   6070             } catch (RemoteException re) {
   6071                 Slog.e(LOG_TAG, "Failed to setMasterMute", re);
   6072             } finally {
   6073                 Binder.restoreCallingIdentity(identity);
   6074             }
   6075         }
   6076     }
   6077 
   6078     @Override
   6079     public boolean isMasterVolumeMuted(ComponentName who) {
   6080         Preconditions.checkNotNull(who, "ComponentName is null");
   6081         synchronized (this) {
   6082             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6083 
   6084             AudioManager audioManager =
   6085                     (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
   6086             return audioManager.isMasterMute();
   6087         }
   6088     }
   6089 
   6090     @Override
   6091     public void setUserIcon(ComponentName who, Bitmap icon) {
   6092         synchronized (this) {
   6093             Preconditions.checkNotNull(who, "ComponentName is null");
   6094             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6095 
   6096             int userId = UserHandle.getCallingUserId();
   6097             long id = Binder.clearCallingIdentity();
   6098             try {
   6099                 mUserManager.setUserIcon(userId, icon);
   6100             } finally {
   6101                 restoreCallingIdentity(id);
   6102             }
   6103         }
   6104     }
   6105 
   6106     @Override
   6107     public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
   6108         Preconditions.checkNotNull(who, "ComponentName is null");
   6109         synchronized (this) {
   6110             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   6111         }
   6112         final int userId = UserHandle.getCallingUserId();
   6113         LockPatternUtils utils = new LockPatternUtils(mContext);
   6114 
   6115         long ident = Binder.clearCallingIdentity();
   6116         try {
   6117             // disallow disabling the keyguard if a password is currently set
   6118             if (disabled && utils.isSecure(userId)) {
   6119                 return false;
   6120             }
   6121             utils.setLockScreenDisabled(disabled, userId);
   6122         } finally {
   6123             Binder.restoreCallingIdentity(ident);
   6124         }
   6125         return true;
   6126     }
   6127 
   6128     @Override
   6129     public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
   6130         int userId = UserHandle.getCallingUserId();
   6131         synchronized (this) {
   6132             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   6133             DevicePolicyData policy = getUserData(userId);
   6134             if (policy.mStatusBarDisabled != disabled) {
   6135                 if (!setStatusBarDisabledInternal(disabled, userId)) {
   6136                     return false;
   6137                 }
   6138                 policy.mStatusBarDisabled = disabled;
   6139                 saveSettingsLocked(userId);
   6140             }
   6141         }
   6142         return true;
   6143     }
   6144 
   6145     private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
   6146         long ident = Binder.clearCallingIdentity();
   6147         try {
   6148             IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
   6149                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
   6150             if (statusBarService != null) {
   6151                 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
   6152                 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
   6153                 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
   6154                 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
   6155                 return true;
   6156             }
   6157         } catch (RemoteException e) {
   6158             Slog.e(LOG_TAG, "Failed to disable the status bar", e);
   6159         } finally {
   6160             Binder.restoreCallingIdentity(ident);
   6161         }
   6162         return false;
   6163     }
   6164 
   6165     /**
   6166      * We need to update the internal state of whether a user has completed setup once. After
   6167      * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
   6168      * as we don't trust any apps that might try to reset it.
   6169      * <p>
   6170      * Unfortunately, we don't know which user's setup state was changed, so we write all of
   6171      * them.
   6172      */
   6173     void updateUserSetupComplete() {
   6174         List<UserInfo> users = mUserManager.getUsers(true);
   6175         ContentResolver resolver = mContext.getContentResolver();
   6176         final int N = users.size();
   6177         for (int i = 0; i < N; i++) {
   6178             int userHandle = users.get(i).id;
   6179             if (Settings.Secure.getIntForUser(resolver, Settings.Secure.USER_SETUP_COMPLETE, 0,
   6180                     userHandle) != 0) {
   6181                 DevicePolicyData policy = getUserData(userHandle);
   6182                 if (!policy.mUserSetupComplete) {
   6183                     policy.mUserSetupComplete = true;
   6184                     synchronized (this) {
   6185                         // The DeviceInitializer was whitelisted but now should be removed.
   6186                         removeDeviceInitializerFromLockTaskPackages(userHandle);
   6187                         saveSettingsLocked(userHandle);
   6188                     }
   6189                 }
   6190             }
   6191         }
   6192     }
   6193 
   6194     private void addDeviceInitializerToLockTaskPackagesLocked(int userHandle) {
   6195         if (hasUserSetupCompleted(userHandle)) {
   6196             return;
   6197         }
   6198 
   6199         final String deviceInitializerPackage = getDeviceInitializer();
   6200         if (deviceInitializerPackage == null) {
   6201             return;
   6202         }
   6203 
   6204         final List<String> packages = getLockTaskPackagesLocked(userHandle);
   6205         if (!packages.contains(deviceInitializerPackage)) {
   6206             packages.add(deviceInitializerPackage);
   6207             setLockTaskPackagesLocked(userHandle, packages);
   6208         }
   6209     }
   6210 
   6211     private void removeDeviceInitializerFromLockTaskPackages(int userHandle) {
   6212         final String deviceInitializerPackage = getDeviceInitializer();
   6213         if (deviceInitializerPackage == null) {
   6214             return;
   6215         }
   6216 
   6217         List<String> packages = getLockTaskPackagesLocked(userHandle);
   6218         if (packages.remove(deviceInitializerPackage)) {
   6219             setLockTaskPackagesLocked(userHandle, packages);
   6220         }
   6221     }
   6222 
   6223     private class SetupContentObserver extends ContentObserver {
   6224 
   6225         private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
   6226                 Settings.Secure.USER_SETUP_COMPLETE);
   6227 
   6228         public SetupContentObserver(Handler handler) {
   6229             super(handler);
   6230         }
   6231 
   6232         void register(ContentResolver resolver) {
   6233             resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
   6234         }
   6235 
   6236         @Override
   6237         public void onChange(boolean selfChange, Uri uri) {
   6238             if (mUserSetupComplete.equals(uri)) {
   6239                 updateUserSetupComplete();
   6240             }
   6241         }
   6242     }
   6243 
   6244     private final class LocalService extends DevicePolicyManagerInternal {
   6245         private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
   6246 
   6247         @Override
   6248         public List<String> getCrossProfileWidgetProviders(int profileId) {
   6249             synchronized (DevicePolicyManagerService.this) {
   6250                 if (mDeviceOwner == null) {
   6251                     return Collections.emptyList();
   6252                 }
   6253                 ComponentName ownerComponent = mDeviceOwner.getProfileOwnerComponent(profileId);
   6254                 if (ownerComponent == null) {
   6255                     return Collections.emptyList();
   6256                 }
   6257 
   6258                 DevicePolicyData policy = getUserDataUnchecked(profileId);
   6259                 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
   6260 
   6261                 if (admin == null || admin.crossProfileWidgetProviders == null
   6262                         || admin.crossProfileWidgetProviders.isEmpty()) {
   6263                     return Collections.emptyList();
   6264                 }
   6265 
   6266                 return admin.crossProfileWidgetProviders;
   6267             }
   6268         }
   6269 
   6270         @Override
   6271         public void addOnCrossProfileWidgetProvidersChangeListener(
   6272                 OnCrossProfileWidgetProvidersChangeListener listener) {
   6273             synchronized (DevicePolicyManagerService.this) {
   6274                 if (mWidgetProviderListeners == null) {
   6275                     mWidgetProviderListeners = new ArrayList<>();
   6276                 }
   6277                 if (!mWidgetProviderListeners.contains(listener)) {
   6278                     mWidgetProviderListeners.add(listener);
   6279                 }
   6280             }
   6281         }
   6282 
   6283         @Override
   6284         public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
   6285             final int userId = UserHandle.getUserId(uid);
   6286             synchronized(DevicePolicyManagerService.this) {
   6287                 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
   6288             }
   6289         }
   6290 
   6291         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
   6292             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
   6293             synchronized (DevicePolicyManagerService.this) {
   6294                 listeners = new ArrayList<>(mWidgetProviderListeners);
   6295             }
   6296             final int listenerCount = listeners.size();
   6297             for (int i = 0; i < listenerCount; i++) {
   6298                 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
   6299                 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
   6300             }
   6301         }
   6302     }
   6303 
   6304     /**
   6305      * Returns true if specified admin is allowed to limit passwords and has a
   6306      * {@code passwordQuality} of at least {@code minPasswordQuality}
   6307      */
   6308     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
   6309         if (admin.passwordQuality < minPasswordQuality) {
   6310             return false;
   6311         }
   6312         return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
   6313     }
   6314 
   6315     @Override
   6316     public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
   6317         if (policy != null && !policy.isValid()) {
   6318             throw new IllegalArgumentException("Invalid system update policy.");
   6319         }
   6320         synchronized (this) {
   6321             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
   6322             if (policy == null) {
   6323                 mDeviceOwner.clearSystemUpdatePolicy();
   6324             } else {
   6325                 mDeviceOwner.setSystemUpdatePolicy(policy);
   6326             }
   6327             mDeviceOwner.writeOwnerFile();
   6328         }
   6329         mContext.sendBroadcastAsUser(
   6330                 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
   6331                 UserHandle.OWNER);
   6332     }
   6333 
   6334     @Override
   6335     public SystemUpdatePolicy getSystemUpdatePolicy() {
   6336         synchronized (this) {
   6337             SystemUpdatePolicy policy =  mDeviceOwner.getSystemUpdatePolicy();
   6338             if (policy != null && !policy.isValid()) {
   6339                 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
   6340                 return null;
   6341             }
   6342             return policy;
   6343         }
   6344     }
   6345 
   6346     /**
   6347      * Checks if the caller of the method is the device owner app or device initialization app.
   6348      *
   6349      * @param callerUid UID of the caller.
   6350      * @return true if the caller is the device owner app or device initializer.
   6351      */
   6352     private boolean isCallerDeviceOwnerOrInitializer(int callerUid) {
   6353         String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
   6354         for (String pkg : pkgs) {
   6355             if (isDeviceOwner(pkg) || isDeviceInitializer(pkg)) {
   6356                 return true;
   6357             }
   6358         }
   6359         return false;
   6360     }
   6361 
   6362     @Override
   6363     public void notifyPendingSystemUpdate(long updateReceivedTime) {
   6364         mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
   6365                 "Only the system update service can broadcast update information");
   6366 
   6367         if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
   6368             Slog.w(LOG_TAG, "Only the system update service in the primary user" +
   6369                     "can broadcast update information.");
   6370             return;
   6371         }
   6372         Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
   6373         intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
   6374                 updateReceivedTime);
   6375 
   6376         synchronized (this) {
   6377             String deviceOwnerPackage = getDeviceOwner();
   6378             if (deviceOwnerPackage == null) {
   6379                 return;
   6380             }
   6381 
   6382             ActivityInfo[] receivers = null;
   6383             try {
   6384                 receivers  = mContext.getPackageManager().getPackageInfo(
   6385                         deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
   6386             } catch (NameNotFoundException e) {
   6387                 Log.e(LOG_TAG, "Cannot find device owner package", e);
   6388             }
   6389             if (receivers != null) {
   6390                 long ident = Binder.clearCallingIdentity();
   6391                 try {
   6392                     for (int i = 0; i < receivers.length; i++) {
   6393                         if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
   6394                             intent.setComponent(new ComponentName(deviceOwnerPackage,
   6395                                     receivers[i].name));
   6396                             mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
   6397                         }
   6398                     }
   6399                 } finally {
   6400                     Binder.restoreCallingIdentity(ident);
   6401                 }
   6402             }
   6403         }
   6404     }
   6405 
   6406     @Override
   6407     public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
   6408         int userId = UserHandle.getCallingUserId();
   6409         synchronized (this) {
   6410             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6411             DevicePolicyData userPolicy = getUserData(userId);
   6412             if (userPolicy.mPermissionPolicy != policy) {
   6413                 userPolicy.mPermissionPolicy = policy;
   6414                 saveSettingsLocked(userId);
   6415             }
   6416         }
   6417     }
   6418 
   6419     @Override
   6420     public int getPermissionPolicy(ComponentName admin) throws RemoteException {
   6421         int userId = UserHandle.getCallingUserId();
   6422         synchronized (this) {
   6423             DevicePolicyData userPolicy = getUserData(userId);
   6424             return userPolicy.mPermissionPolicy;
   6425         }
   6426     }
   6427 
   6428     @Override
   6429     public boolean setPermissionGrantState(ComponentName admin, String packageName,
   6430             String permission, int grantState) throws RemoteException {
   6431         UserHandle user = Binder.getCallingUserHandle();
   6432         synchronized (this) {
   6433             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6434             long ident = Binder.clearCallingIdentity();
   6435             try {
   6436                 final ApplicationInfo ai = AppGlobals.getPackageManager()
   6437                         .getApplicationInfo(packageName, 0, user.getIdentifier());
   6438                 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
   6439                 if (targetSdkVersion < android.os.Build.VERSION_CODES.M) {
   6440                     return false;
   6441                 }
   6442                 final PackageManager packageManager = mContext.getPackageManager();
   6443                 switch (grantState) {
   6444                     case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
   6445                         packageManager.grantRuntimePermission(packageName, permission, user);
   6446                         packageManager.updatePermissionFlags(permission, packageName,
   6447                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
   6448                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
   6449                     } break;
   6450 
   6451                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
   6452                         packageManager.revokeRuntimePermission(packageName,
   6453                                 permission, user);
   6454                         packageManager.updatePermissionFlags(permission, packageName,
   6455                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
   6456                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
   6457                     } break;
   6458 
   6459                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
   6460                         packageManager.updatePermissionFlags(permission, packageName,
   6461                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
   6462                     } break;
   6463                 }
   6464                 return true;
   6465             } catch (SecurityException se) {
   6466                 return false;
   6467             } finally {
   6468                 Binder.restoreCallingIdentity(ident);
   6469             }
   6470         }
   6471     }
   6472 
   6473     @Override
   6474     public int getPermissionGrantState(ComponentName admin, String packageName,
   6475             String permission) throws RemoteException {
   6476         PackageManager packageManager = mContext.getPackageManager();
   6477 
   6478         UserHandle user = Binder.getCallingUserHandle();
   6479         synchronized (this) {
   6480             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
   6481             long ident = Binder.clearCallingIdentity();
   6482             try {
   6483                 int granted = AppGlobals.getPackageManager().checkPermission(permission,
   6484                         packageName, user.getIdentifier());
   6485                 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
   6486                 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
   6487                         != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
   6488                     // Not controlled by policy
   6489                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
   6490                 } else {
   6491                     // Policy controlled so return result based on permission grant state
   6492                     return granted == PackageManager.PERMISSION_GRANTED
   6493                             ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
   6494                             : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
   6495                 }
   6496             } finally {
   6497                 Binder.restoreCallingIdentity(ident);
   6498             }
   6499         }
   6500     }
   6501 }
   6502