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