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