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