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