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