DevicePolicyManagerService.java revision 6a8df9c25e6869d171af71f49ed87847f0b212a2
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.BIND_DEVICE_ADMIN;
20import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
21import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
22import static android.app.ActivityManager.USER_OP_SUCCESS;
23import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER;
24import static android.app.admin.DevicePolicyManager.CODE_ACCOUNTS_NOT_EMPTY;
25import static android.app.admin.DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED;
26import static android.app.admin.DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE;
27import static android.app.admin.DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED;
28import static android.app.admin.DevicePolicyManager.CODE_HAS_DEVICE_OWNER;
29import static android.app.admin.DevicePolicyManager.CODE_HAS_PAIRED;
30import static android.app.admin.DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED;
31import static android.app.admin.DevicePolicyManager.CODE_NONSYSTEM_USER_EXISTS;
32import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER;
33import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT;
34import static android.app.admin.DevicePolicyManager.CODE_OK;
35import static android.app.admin.DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
36import static android.app.admin.DevicePolicyManager.CODE_SYSTEM_USER;
37import static android.app.admin.DevicePolicyManager.CODE_USER_HAS_PROFILE_OWNER;
38import static android.app.admin.DevicePolicyManager.CODE_USER_NOT_RUNNING;
39import static android.app.admin.DevicePolicyManager.CODE_USER_SETUP_COMPLETED;
40import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
41import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL;
42import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
43import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP;
44import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE;
45import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES;
46import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS;
47import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT;
48import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED;
49import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
50import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
51import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
52import static android.app.admin.DevicePolicyManager.START_USER_IN_BACKGROUND;
53import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
54import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
55import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
56import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
57import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
58import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
59import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
60import static org.xmlpull.v1.XmlPullParser.END_TAG;
61import static org.xmlpull.v1.XmlPullParser.TEXT;
62
63import android.Manifest.permission;
64import android.accessibilityservice.AccessibilityServiceInfo;
65import android.accounts.Account;
66import android.accounts.AccountManager;
67import android.annotation.NonNull;
68import android.annotation.Nullable;
69import android.annotation.UserIdInt;
70import android.app.Activity;
71import android.app.ActivityManager;
72import android.app.ActivityManagerInternal;
73import android.app.AlarmManager;
74import android.app.AppGlobals;
75import android.app.IActivityManager;
76import android.app.IApplicationThread;
77import android.app.IServiceConnection;
78import android.app.Notification;
79import android.app.NotificationManager;
80import android.app.PendingIntent;
81import android.app.StatusBarManager;
82import android.app.admin.DeviceAdminInfo;
83import android.app.admin.DeviceAdminReceiver;
84import android.app.admin.DevicePolicyManager;
85import android.app.admin.DevicePolicyManagerInternal;
86import android.app.admin.NetworkEvent;
87import android.app.admin.PasswordMetrics;
88import android.app.admin.SecurityLog;
89import android.app.admin.SecurityLog.SecurityEvent;
90import android.app.admin.SystemUpdateInfo;
91import android.app.admin.SystemUpdatePolicy;
92import android.app.backup.IBackupManager;
93import android.app.trust.TrustManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.Intent;
98import android.content.IntentFilter;
99import android.content.pm.ActivityInfo;
100import android.content.pm.ApplicationInfo;
101import android.content.pm.IPackageDataObserver;
102import android.content.pm.IPackageManager;
103import android.content.pm.PackageInfo;
104import android.content.pm.PackageManager;
105import android.content.pm.PackageManagerInternal;
106import android.content.pm.PackageManager.NameNotFoundException;
107import android.content.pm.ParceledListSlice;
108import android.content.pm.PermissionInfo;
109import android.content.pm.ResolveInfo;
110import android.content.pm.ServiceInfo;
111import android.content.pm.StringParceledListSlice;
112import android.content.pm.UserInfo;
113import android.content.res.Resources;
114import android.database.ContentObserver;
115import android.graphics.Bitmap;
116import android.graphics.Color;
117import android.media.AudioManager;
118import android.media.IAudioService;
119import android.net.ConnectivityManager;
120import android.net.IIpConnectivityMetrics;
121import android.net.ProxyInfo;
122import android.net.Uri;
123import android.net.metrics.IpConnectivityLog;
124import android.net.wifi.WifiInfo;
125import android.net.wifi.WifiManager;
126import android.os.Binder;
127import android.os.Build;
128import android.os.Bundle;
129import android.os.Environment;
130import android.os.FileUtils;
131import android.os.Handler;
132import android.os.IBinder;
133import android.os.Looper;
134import android.os.ParcelFileDescriptor;
135import android.os.PersistableBundle;
136import android.os.PowerManager;
137import android.os.PowerManagerInternal;
138import android.os.Process;
139import android.os.RecoverySystem;
140import android.os.RemoteCallback;
141import android.os.RemoteException;
142import android.os.ServiceManager;
143import android.os.SystemClock;
144import android.os.SystemProperties;
145import android.os.UserHandle;
146import android.os.UserManager;
147import android.os.UserManagerInternal;
148import android.os.storage.StorageManager;
149import android.provider.ContactsContract.QuickContact;
150import android.provider.ContactsInternal;
151import android.provider.Settings;
152import android.provider.Settings.Global;
153import android.security.IKeyChainAliasCallback;
154import android.security.IKeyChainService;
155import android.security.KeyChain;
156import android.security.KeyChain.KeyChainConnection;
157import android.security.keystore.KeyGenParameterSpec;
158import android.security.keystore.ParcelableKeyGenParameterSpec;
159import android.security.KeyStore;
160import android.service.persistentdata.PersistentDataBlockManager;
161import android.telephony.TelephonyManager;
162import android.text.TextUtils;
163import android.util.ArrayMap;
164import android.util.ArraySet;
165import android.util.Log;
166import android.util.Pair;
167import android.util.Slog;
168import android.util.SparseArray;
169import android.util.Xml;
170import android.view.IWindowManager;
171import android.view.accessibility.AccessibilityManager;
172import android.view.accessibility.IAccessibilityManager;
173import android.view.inputmethod.InputMethodInfo;
174import android.view.inputmethod.InputMethodManager;
175
176import com.android.internal.R;
177import com.android.internal.annotations.GuardedBy;
178import com.android.internal.annotations.VisibleForTesting;
179import com.android.internal.logging.MetricsLogger;
180import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
181import com.android.internal.notification.SystemNotificationChannels;
182import com.android.internal.os.BackgroundThread;
183import com.android.internal.statusbar.IStatusBarService;
184import com.android.internal.util.DumpUtils;
185import com.android.internal.util.FastXmlSerializer;
186import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
187import com.android.internal.util.JournaledFile;
188import com.android.internal.util.Preconditions;
189import com.android.internal.util.XmlUtils;
190import com.android.internal.widget.LockPatternUtils;
191import com.android.server.LocalServices;
192import com.android.server.SystemService;
193import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
194import com.android.server.pm.UserRestrictionsUtils;
195import com.google.android.collect.Sets;
196
197import org.xmlpull.v1.XmlPullParser;
198import org.xmlpull.v1.XmlPullParserException;
199import org.xmlpull.v1.XmlSerializer;
200
201import java.io.File;
202import java.io.FileDescriptor;
203import java.io.FileInputStream;
204import java.io.FileNotFoundException;
205import java.io.FileOutputStream;
206import java.io.IOException;
207import java.io.PrintWriter;
208import java.lang.IllegalStateException;
209import java.lang.reflect.Constructor;
210import java.nio.charset.StandardCharsets;
211import java.text.DateFormat;
212import java.util.ArrayList;
213import java.util.Arrays;
214import java.util.Collection;
215import java.util.Collections;
216import java.util.Date;
217import java.util.List;
218import java.util.Map.Entry;
219import java.util.Set;
220import java.util.concurrent.TimeUnit;
221import java.util.concurrent.atomic.AtomicBoolean;
222import java.util.function.Function;
223
224/**
225 * Implementation of the device policy APIs.
226 */
227public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
228
229    protected static final String LOG_TAG = "DevicePolicyManager";
230
231    private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
232
233    private static final String DEVICE_POLICIES_XML = "device_policies.xml";
234
235    private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
236
237    private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
238
239    private static final String TAG_LOCK_TASK_FEATURES = "lock-task-features";
240
241    private static final String TAG_STATUS_BAR = "statusbar";
242
243    private static final String ATTR_DISABLED = "disabled";
244
245    private static final String ATTR_NAME = "name";
246
247    private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
248            "do-not-ask-credentials-on-boot";
249
250    private static final String TAG_AFFILIATION_ID = "affiliation-id";
251
252    private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval";
253
254    private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request";
255
256    private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval";
257
258    private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
259
260    private static final String TAG_CURRENT_INPUT_METHOD_SET = "current-ime-set";
261
262    private static final String TAG_OWNER_INSTALLED_CA_CERT = "owner-installed-ca-cert";
263
264    private static final String ATTR_ID = "id";
265
266    private static final String ATTR_VALUE = "value";
267
268    private static final String ATTR_ALIAS = "alias";
269
270    private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
271
272    private static final String TAG_PASSWORD_TOKEN_HANDLE = "password-token";
273
274    private static final String TAG_PASSWORD_VALIDITY = "password-validity";
275
276    private static final int REQUEST_EXPIRE_PASSWORD = 5571;
277
278    private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);
279
280    private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
281
282    private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
283            = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
284
285    private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
286    private static final String ATTR_SETUP_COMPLETE = "setup-complete";
287    private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
288    private static final String ATTR_PERMISSION_POLICY = "permission-policy";
289    private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
290            "device-provisioning-config-applied";
291    private static final String ATTR_DEVICE_PAIRED = "device-paired";
292    private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
293    private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
294            = "application-restrictions-manager";
295
296    private static final String MANAGED_PROVISIONING_PKG = "com.android.managedprovisioning";
297
298    // Comprehensive list of delegations.
299    private static final String DELEGATIONS[] = {
300        DELEGATION_CERT_INSTALL,
301        DELEGATION_APP_RESTRICTIONS,
302        DELEGATION_BLOCK_UNINSTALL,
303        DELEGATION_ENABLE_SYSTEM_APP,
304        DELEGATION_KEEP_UNINSTALLED_PACKAGES,
305        DELEGATION_PACKAGE_ACCESS,
306        DELEGATION_PERMISSION_GRANT,
307        DELEGATION_INSTALL_EXISTING_PACKAGE,
308        DELEGATION_KEEP_UNINSTALLED_PACKAGES
309    };
310
311    /**
312     *  System property whose value is either "true" or "false", indicating whether
313     *  device owner is present.
314     */
315    private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
316
317    private static final int STATUS_BAR_DISABLE_MASK =
318            StatusBarManager.DISABLE_EXPAND |
319            StatusBarManager.DISABLE_NOTIFICATION_ICONS |
320            StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
321            StatusBarManager.DISABLE_SEARCH;
322
323    private static final int STATUS_BAR_DISABLE2_MASK =
324            StatusBarManager.DISABLE2_QUICK_SETTINGS;
325
326    private static final Set<String> SECURE_SETTINGS_WHITELIST;
327    private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
328    private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
329    private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
330    private static final Set<String> SYSTEM_SETTINGS_WHITELIST;
331    static {
332        SECURE_SETTINGS_WHITELIST = new ArraySet<>();
333        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
334        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
335        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
336
337        SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
338        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
339        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
340
341        GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
342        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
343        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
344        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
345        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
346        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
347        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
348        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
349        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
350
351        GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
352        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
353        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
354        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
355        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
356        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
357
358        SYSTEM_SETTINGS_WHITELIST = new ArraySet<>();
359        SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS);
360        SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE);
361        SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_OFF_TIMEOUT);
362    }
363
364    /**
365     * Keyguard features that when set on a profile affect the profile content or challenge only.
366     * These cannot be set on the managed profile's parent DPM instance
367     */
368    private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
369            DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
370
371    /** Keyguard features that are allowed to be set on a managed profile */
372    private static final int PROFILE_KEYGUARD_FEATURES =
373            PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
374
375    private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
376
377    /**
378     * Minimum timeout in milliseconds after which unlocking with weak auth times out,
379     * i.e. the user has to use a strong authentication method like password, PIN or pattern.
380     */
381    private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
382
383    /**
384     * Strings logged with {@link
385     * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}.
386     */
387    private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
388    private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
389
390    final Context mContext;
391    final Injector mInjector;
392    final IPackageManager mIPackageManager;
393    final UserManager mUserManager;
394    final UserManagerInternal mUserManagerInternal;
395    final TelephonyManager mTelephonyManager;
396    private final LockPatternUtils mLockPatternUtils;
397    private final DevicePolicyConstants mConstants;
398    private final DeviceAdminServiceController mDeviceAdminServiceController;
399    private final OverlayPackagesProvider mOverlayPackagesProvider;
400
401    /**
402     * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
403     * is requested for user u.
404     */
405    private final Set<Pair<String, Integer>> mPackagesToRemove =
406            new ArraySet<Pair<String, Integer>>();
407
408    final LocalService mLocalService;
409
410    // Stores and loads state on device and profile owners.
411    @VisibleForTesting
412    final Owners mOwners;
413
414    private final Binder mToken = new Binder();
415
416    /**
417     * Whether or not device admin feature is supported. If it isn't return defaults for all
418     * public methods.
419     */
420    boolean mHasFeature;
421
422    /**
423     * Whether or not this device is a watch.
424     */
425    boolean mIsWatch;
426
427    private final CertificateMonitor mCertificateMonitor;
428    private final SecurityLogMonitor mSecurityLogMonitor;
429    private NetworkLogger mNetworkLogger;
430
431    private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
432    private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
433
434    private SetupContentObserver mSetupContentObserver;
435
436    private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
437        @Override
438        public void run() {
439            if(mRemoteBugreportServiceIsActive.get()) {
440                onBugreportFailed();
441            }
442        }
443    };
444
445    /** Listens only if mHasFeature == true. */
446    private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
447
448        @Override
449        public void onReceive(Context context, Intent intent) {
450            if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
451                    && mRemoteBugreportServiceIsActive.get()) {
452                onBugreportFinished(intent);
453            }
454        }
455    };
456
457    /** Listens only if mHasFeature == true. */
458    private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
459
460        @Override
461        public void onReceive(Context context, Intent intent) {
462            String action = intent.getAction();
463            mInjector.getNotificationManager().cancel(LOG_TAG,
464                    RemoteBugreportUtils.NOTIFICATION_ID);
465            if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
466                onBugreportSharingAccepted();
467            } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
468                onBugreportSharingDeclined();
469            }
470            mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
471        }
472    };
473
474    public static final class Lifecycle extends SystemService {
475        private BaseIDevicePolicyManager mService;
476
477        public Lifecycle(Context context) {
478            super(context);
479            String dpmsClassName = context.getResources()
480                    .getString(R.string.config_deviceSpecificDevicePolicyManagerService);
481            if (TextUtils.isEmpty(dpmsClassName)) {
482                dpmsClassName = DevicePolicyManagerService.class.getName();
483            }
484            try {
485                Class serviceClass = Class.forName(dpmsClassName);
486                Constructor constructor = serviceClass.getConstructor(Context.class);
487                mService = (BaseIDevicePolicyManager) constructor.newInstance(context);
488            } catch (Exception e) {
489                throw new IllegalStateException(
490                    "Failed to instantiate DevicePolicyManagerService with class name: "
491                    + dpmsClassName, e);
492            }
493        }
494
495        @Override
496        public void onStart() {
497            publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
498        }
499
500        @Override
501        public void onBootPhase(int phase) {
502            mService.systemReady(phase);
503        }
504
505        @Override
506        public void onStartUser(int userHandle) {
507            mService.handleStartUser(userHandle);
508        }
509
510        @Override
511        public void onUnlockUser(int userHandle) {
512            mService.handleUnlockUser(userHandle);
513        }
514
515        @Override
516        public void onStopUser(int userHandle) {
517            mService.handleStopUser(userHandle);
518        }
519    }
520
521    public static class DevicePolicyData {
522        @NonNull PasswordMetrics mActivePasswordMetrics = new PasswordMetrics();
523        int mFailedPasswordAttempts = 0;
524        boolean mPasswordStateHasBeenSetSinceBoot = false;
525        boolean mPasswordValidAtLastCheckpoint = false;
526
527        int mUserHandle;
528        int mPasswordOwner = -1;
529        long mLastMaximumTimeToLock = -1;
530        boolean mUserSetupComplete = false;
531        boolean mPaired = false;
532        int mUserProvisioningState;
533        int mPermissionPolicy;
534
535        boolean mDeviceProvisioningConfigApplied = false;
536
537        final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
538        final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
539        final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
540
541        // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
542        final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
543
544        // This is the list of component allowed to start lock task mode.
545        List<String> mLockTaskPackages = new ArrayList<>();
546
547        // Bitfield of feature flags to be enabled during LockTask mode.
548        int mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
549
550        boolean mStatusBarDisabled = false;
551
552        ComponentName mRestrictionsProvider;
553
554        // Map of delegate package to delegation scopes
555        final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>();
556
557        boolean doNotAskCredentialsOnBoot = false;
558
559        Set<String> mAffiliationIds = new ArraySet<>();
560
561        long mLastSecurityLogRetrievalTime = -1;
562
563        long mLastBugReportRequestTime = -1;
564
565        long mLastNetworkLogsRetrievalTime = -1;
566
567        boolean mCurrentInputMethodSet = false;
568
569        // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
570        Set<String> mOwnerInstalledCaCerts = new ArraySet<>();
571
572        // Used for initialization of users created by createAndManageUser.
573        boolean mAdminBroadcastPending = false;
574        PersistableBundle mInitBundle = null;
575
576        long mPasswordTokenHandle = 0;
577
578        public DevicePolicyData(int userHandle) {
579            mUserHandle = userHandle;
580        }
581    }
582
583    final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
584
585    final Handler mHandler;
586    final Handler mBackgroundHandler;
587
588    /** Listens only if mHasFeature == true. */
589    final BroadcastReceiver mReceiver = new BroadcastReceiver() {
590        @Override
591        public void onReceive(Context context, Intent intent) {
592            final String action = intent.getAction();
593            final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
594                    getSendingUserId());
595
596            /*
597             * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
598             * however it's too early in the boot process to register with IIpConnectivityMetrics
599             * to listen for events.
600             */
601            if (Intent.ACTION_USER_STARTED.equals(action)
602                    && userHandle == mOwners.getDeviceOwnerUserId()) {
603                synchronized (DevicePolicyManagerService.this) {
604                    if (isNetworkLoggingEnabledInternalLocked()) {
605                        setNetworkLoggingActiveInternal(true);
606                    }
607                }
608            }
609            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
610                    && userHandle == mOwners.getDeviceOwnerUserId()
611                    && getDeviceOwnerRemoteBugreportUri() != null) {
612                IntentFilter filterConsent = new IntentFilter();
613                filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
614                filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
615                mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
616                mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
617                        RemoteBugreportUtils.NOTIFICATION_ID,
618                        RemoteBugreportUtils.buildNotification(mContext,
619                                DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
620                                UserHandle.ALL);
621            }
622            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
623                    || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
624                if (VERBOSE_LOG) {
625                    Slog.v(LOG_TAG, "Sending password expiration notifications for action "
626                            + action + " for user " + userHandle);
627                }
628                mHandler.post(new Runnable() {
629                    @Override
630                    public void run() {
631                        handlePasswordExpirationNotification(userHandle);
632                    }
633                });
634            }
635
636            if (Intent.ACTION_USER_ADDED.equals(action)) {
637                sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
638                synchronized (DevicePolicyManagerService.this) {
639                    // It might take a while for the user to become affiliated. Make security
640                    // and network logging unavailable in the meantime.
641                    maybePauseDeviceWideLoggingLocked();
642                }
643            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
644                sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
645                synchronized (DevicePolicyManagerService.this) {
646                    // Check whether the user is affiliated, *before* removing its data.
647                    boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
648                    removeUserData(userHandle);
649                    if (!isRemovedUserAffiliated) {
650                        // We discard the logs when unaffiliated users are deleted (so that the
651                        // device owner cannot retrieve data about that user after it's gone).
652                        discardDeviceWideLogsLocked();
653                        // Resume logging if all remaining users are affiliated.
654                        maybeResumeDeviceWideLoggingLocked();
655                    }
656                }
657            } else if (Intent.ACTION_USER_STARTED.equals(action)) {
658                synchronized (DevicePolicyManagerService.this) {
659                    maybeSendAdminEnabledBroadcastLocked(userHandle);
660                    // Reset the policy data
661                    mUserData.remove(userHandle);
662                }
663                handlePackagesChanged(null /* check all admins */, userHandle);
664            } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
665                synchronized (DevicePolicyManagerService.this) {
666                    maybeSendAdminEnabledBroadcastLocked(userHandle);
667                }
668            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
669                handlePackagesChanged(null /* check all admins */, userHandle);
670            } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
671                    || (Intent.ACTION_PACKAGE_ADDED.equals(action)
672                            && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
673                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
674            } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
675                    && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
676                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
677            } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
678                clearWipeProfileNotification();
679            }
680        }
681
682        private void sendUserAddedOrRemovedCommand(String action, int userHandle) {
683            synchronized (DevicePolicyManagerService.this) {
684                ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
685                if (deviceOwner != null) {
686                    Bundle extras = new Bundle();
687                    extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
688                    sendAdminCommandLocked(deviceOwner, action, extras, null);
689                }
690            }
691        }
692    };
693
694    static class ActiveAdmin {
695        private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
696        private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
697        private static final String TAG_DISABLE_CAMERA = "disable-camera";
698        private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
699        private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
700        private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
701                = "disable-bt-contacts-sharing";
702        private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
703        private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
704        private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
705        private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
706        private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled";
707        private static final String TAG_ACCOUNT_TYPE = "account-type";
708        private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
709                = "permitted-accessiblity-services";
710        private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
711        private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
712        private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
713        private static final String TAG_TRUST_AGENT_COMPONENT = "component";
714        private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
715        private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
716        private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
717        private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
718        private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
719        private static final String TAG_PERMITTED_IMES = "permitted-imes";
720        private static final String TAG_PERMITTED_NOTIFICATION_LISTENERS =
721                "permitted-notification-listeners";
722        private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
723        private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
724        private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
725        private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
726        private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
727        private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
728        private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
729        private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
730        private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
731        private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
732        private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
733        private static final String ATTR_VALUE = "value";
734        private static final String TAG_PASSWORD_QUALITY = "password-quality";
735        private static final String TAG_POLICIES = "policies";
736        private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
737                "cross-profile-widget-providers";
738        private static final String TAG_PROVIDER = "provider";
739        private static final String TAG_PACKAGE_LIST_ITEM  = "item";
740        private static final String TAG_KEEP_UNINSTALLED_PACKAGES  = "keep-uninstalled-packages";
741        private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
742        private static final String TAG_DEFAULT_ENABLED_USER_RESTRICTIONS =
743                "default-enabled-user-restrictions";
744        private static final String TAG_RESTRICTION = "restriction";
745        private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
746        private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
747        private static final String TAG_PARENT_ADMIN = "parent-admin";
748        private static final String TAG_ORGANIZATION_COLOR = "organization-color";
749        private static final String TAG_ORGANIZATION_NAME = "organization-name";
750        private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification";
751        private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications";
752        private static final String TAG_IS_LOGOUT_ENABLED = "is_logout_enabled";
753
754        final DeviceAdminInfo info;
755
756
757        static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
758        int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
759
760        static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
761        static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
762        static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
763        static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
764        static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
765        static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
766        static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
767        @NonNull
768        PasswordMetrics minimumPasswordMetrics = new PasswordMetrics(
769                PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH,
770                DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE,
771                DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC,
772                DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER);
773
774        static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
775        long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
776
777        long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
778
779        static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
780        int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
781
782        static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
783        long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
784
785        static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
786        long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
787
788        static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
789
790        int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
791
792        boolean encryptionRequested = false;
793        boolean testOnlyAdmin = false;
794        boolean disableCamera = false;
795        boolean disableCallerId = false;
796        boolean disableContactsSearch = false;
797        boolean disableBluetoothContactSharing = true;
798        boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
799        boolean requireAutoTime = false; // Can only be set by a device owner.
800        boolean forceEphemeralUsers = false; // Can only be set by a device owner.
801        boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner.
802        boolean isLogoutEnabled = false; // Can only be set by a device owner.
803
804        // one notification after enabling + one more after reboots
805        static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 2;
806        int numNetworkLoggingNotifications = 0;
807        long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch
808
809        ActiveAdmin parentAdmin;
810        final boolean isParent;
811
812        static class TrustAgentInfo {
813            public PersistableBundle options;
814            TrustAgentInfo(PersistableBundle bundle) {
815                options = bundle;
816            }
817        }
818
819        final Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
820
821        // The list of permitted accessibility services package namesas set by a profile
822        // or device owner. Null means all accessibility services are allowed, empty means
823        // none except system services are allowed.
824        List<String> permittedAccessiblityServices;
825
826        // The list of permitted input methods package names as set by a profile or device owner.
827        // Null means all input methods are allowed, empty means none except system imes are
828        // allowed.
829        List<String> permittedInputMethods;
830
831        // The list of packages allowed to use a NotificationListenerService to receive events for
832        // notifications from this user. Null means that all packages are allowed. Empty list means
833        // that only packages from the system are allowed.
834        List<String> permittedNotificationListeners;
835
836        // List of package names to keep cached.
837        List<String> keepUninstalledPackages;
838
839        // TODO: review implementation decisions with frameworks team
840        boolean specifiesGlobalProxy = false;
841        String globalProxySpec = null;
842        String globalProxyExclusionList = null;
843
844        ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
845
846        List<String> crossProfileWidgetProviders;
847
848        Bundle userRestrictions;
849
850        // User restrictions that have already been enabled by default for this admin (either when
851        // setting the device or profile owner, or during a system update if one of those "enabled
852        // by default" restrictions is newly added).
853        final Set<String> defaultEnabledRestrictionsAlreadySet = new ArraySet<>();
854
855        // Support text provided by the admin to display to the user.
856        CharSequence shortSupportMessage = null;
857        CharSequence longSupportMessage = null;
858
859        // Background color of confirm credentials screen. Default: teal.
860        static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
861        int organizationColor = DEF_ORGANIZATION_COLOR;
862
863        // Default title of confirm credentials screen
864        String organizationName = null;
865
866        ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
867            info = _info;
868            isParent = parent;
869        }
870
871        ActiveAdmin getParentActiveAdmin() {
872            Preconditions.checkState(!isParent);
873
874            if (parentAdmin == null) {
875                parentAdmin = new ActiveAdmin(info, /* parent */ true);
876            }
877            return parentAdmin;
878        }
879
880        boolean hasParentActiveAdmin() {
881            return parentAdmin != null;
882        }
883
884        int getUid() { return info.getActivityInfo().applicationInfo.uid; }
885
886        public UserHandle getUserHandle() {
887            return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
888        }
889
890        void writeToXml(XmlSerializer out)
891                throws IllegalArgumentException, IllegalStateException, IOException {
892            out.startTag(null, TAG_POLICIES);
893            info.writePoliciesToXml(out);
894            out.endTag(null, TAG_POLICIES);
895            if (minimumPasswordMetrics.quality != PASSWORD_QUALITY_UNSPECIFIED) {
896                out.startTag(null, TAG_PASSWORD_QUALITY);
897                out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality));
898                out.endTag(null, TAG_PASSWORD_QUALITY);
899                if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) {
900                    out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
901                    out.attribute(
902                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length));
903                    out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
904                }
905                if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
906                    out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
907                    out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
908                    out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
909                }
910                if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
911                    out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
912                    out.attribute(
913                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase));
914                    out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
915                }
916                if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
917                    out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
918                    out.attribute(
919                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase));
920                    out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
921                }
922                if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) {
923                    out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
924                    out.attribute(
925                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters));
926                    out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
927                }
928                if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
929                    out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
930                    out.attribute(
931                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric));
932                    out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
933                }
934                if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
935                    out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
936                    out.attribute(
937                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols));
938                    out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
939                }
940                if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
941                    out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
942                    out.attribute(
943                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter));
944                    out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
945                }
946            }
947            if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
948                out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
949                out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
950                out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
951            }
952            if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
953                out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
954                out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
955                out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
956            }
957            if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
958                out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
959                out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
960                out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
961            }
962            if (specifiesGlobalProxy) {
963                out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
964                out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
965                out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
966                if (globalProxySpec != null) {
967                    out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
968                    out.attribute(null, ATTR_VALUE, globalProxySpec);
969                    out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
970                }
971                if (globalProxyExclusionList != null) {
972                    out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
973                    out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
974                    out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
975                }
976            }
977            if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
978                out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
979                out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
980                out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
981            }
982            if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
983                out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
984                out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
985                out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
986            }
987            if (encryptionRequested) {
988                out.startTag(null, TAG_ENCRYPTION_REQUESTED);
989                out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
990                out.endTag(null, TAG_ENCRYPTION_REQUESTED);
991            }
992            if (testOnlyAdmin) {
993                out.startTag(null, TAG_TEST_ONLY_ADMIN);
994                out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
995                out.endTag(null, TAG_TEST_ONLY_ADMIN);
996            }
997            if (disableCamera) {
998                out.startTag(null, TAG_DISABLE_CAMERA);
999                out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
1000                out.endTag(null, TAG_DISABLE_CAMERA);
1001            }
1002            if (disableCallerId) {
1003                out.startTag(null, TAG_DISABLE_CALLER_ID);
1004                out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
1005                out.endTag(null, TAG_DISABLE_CALLER_ID);
1006            }
1007            if (disableContactsSearch) {
1008                out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
1009                out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
1010                out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
1011            }
1012            if (!disableBluetoothContactSharing) {
1013                out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
1014                out.attribute(null, ATTR_VALUE,
1015                        Boolean.toString(disableBluetoothContactSharing));
1016                out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
1017            }
1018            if (disableScreenCapture) {
1019                out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
1020                out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
1021                out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
1022            }
1023            if (requireAutoTime) {
1024                out.startTag(null, TAG_REQUIRE_AUTO_TIME);
1025                out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
1026                out.endTag(null, TAG_REQUIRE_AUTO_TIME);
1027            }
1028            if (forceEphemeralUsers) {
1029                out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
1030                out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
1031                out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
1032            }
1033            if (isNetworkLoggingEnabled) {
1034                out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
1035                out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled));
1036                out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS,
1037                        Integer.toString(numNetworkLoggingNotifications));
1038                out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION,
1039                        Long.toString(lastNetworkLoggingNotificationTimeMs));
1040                out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
1041            }
1042            if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
1043                out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1044                out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
1045                out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1046            }
1047            if (!accountTypesWithManagementDisabled.isEmpty()) {
1048                out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
1049                writeAttributeValuesToXml(
1050                        out, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1051                out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
1052            }
1053            if (!trustAgentInfos.isEmpty()) {
1054                Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
1055                out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1056                for (Entry<String, TrustAgentInfo> entry : set) {
1057                    TrustAgentInfo trustAgentInfo = entry.getValue();
1058                    out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
1059                    out.attribute(null, ATTR_VALUE, entry.getKey());
1060                    if (trustAgentInfo.options != null) {
1061                        out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1062                        try {
1063                            trustAgentInfo.options.saveToXml(out);
1064                        } catch (XmlPullParserException e) {
1065                            Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
1066                        }
1067                        out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1068                    }
1069                    out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
1070                }
1071                out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1072            }
1073            if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
1074                out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1075                writeAttributeValuesToXml(out, TAG_PROVIDER, crossProfileWidgetProviders);
1076                out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1077            }
1078            writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
1079                    permittedAccessiblityServices);
1080            writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
1081            writePackageListToXml(out, TAG_PERMITTED_NOTIFICATION_LISTENERS,
1082                    permittedNotificationListeners);
1083            writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
1084            if (hasUserRestrictions()) {
1085                UserRestrictionsUtils.writeRestrictions(
1086                        out, userRestrictions, TAG_USER_RESTRICTIONS);
1087            }
1088            if (!defaultEnabledRestrictionsAlreadySet.isEmpty()) {
1089                out.startTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1090                writeAttributeValuesToXml(
1091                        out, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1092                out.endTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1093            }
1094            if (!TextUtils.isEmpty(shortSupportMessage)) {
1095                out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1096                out.text(shortSupportMessage.toString());
1097                out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1098            }
1099            if (!TextUtils.isEmpty(longSupportMessage)) {
1100                out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
1101                out.text(longSupportMessage.toString());
1102                out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
1103            }
1104            if (parentAdmin != null) {
1105                out.startTag(null, TAG_PARENT_ADMIN);
1106                parentAdmin.writeToXml(out);
1107                out.endTag(null, TAG_PARENT_ADMIN);
1108            }
1109            if (organizationColor != DEF_ORGANIZATION_COLOR) {
1110                out.startTag(null, TAG_ORGANIZATION_COLOR);
1111                out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
1112                out.endTag(null, TAG_ORGANIZATION_COLOR);
1113            }
1114            if (organizationName != null) {
1115                out.startTag(null, TAG_ORGANIZATION_NAME);
1116                out.text(organizationName);
1117                out.endTag(null, TAG_ORGANIZATION_NAME);
1118            }
1119            if (isLogoutEnabled) {
1120                out.startTag(null, TAG_IS_LOGOUT_ENABLED);
1121                out.attribute(null, ATTR_VALUE, Boolean.toString(isLogoutEnabled));
1122                out.endTag(null, TAG_IS_LOGOUT_ENABLED);
1123            }
1124        }
1125
1126        void writePackageListToXml(XmlSerializer out, String outerTag,
1127                List<String> packageList)
1128                throws IllegalArgumentException, IllegalStateException, IOException {
1129            if (packageList == null) {
1130                return;
1131            }
1132
1133            out.startTag(null, outerTag);
1134            writeAttributeValuesToXml(out, TAG_PACKAGE_LIST_ITEM, packageList);
1135            out.endTag(null, outerTag);
1136        }
1137
1138        void writeAttributeValuesToXml(XmlSerializer out, String tag,
1139                @NonNull Collection<String> values) throws IOException {
1140            for (String value : values) {
1141                out.startTag(null, tag);
1142                out.attribute(null, ATTR_VALUE, value);
1143                out.endTag(null, tag);
1144            }
1145        }
1146
1147        void readFromXml(XmlPullParser parser)
1148                throws XmlPullParserException, IOException {
1149            int outerDepth = parser.getDepth();
1150            int type;
1151            while ((type=parser.next()) != END_DOCUMENT
1152                   && (type != END_TAG || parser.getDepth() > outerDepth)) {
1153                if (type == END_TAG || type == TEXT) {
1154                    continue;
1155                }
1156                String tag = parser.getName();
1157                if (TAG_POLICIES.equals(tag)) {
1158                    info.readPoliciesFromXml(parser);
1159                } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
1160                    minimumPasswordMetrics.quality = Integer.parseInt(
1161                            parser.getAttributeValue(null, ATTR_VALUE));
1162                } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
1163                    minimumPasswordMetrics.length = Integer.parseInt(
1164                            parser.getAttributeValue(null, ATTR_VALUE));
1165                } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
1166                    passwordHistoryLength = Integer.parseInt(
1167                            parser.getAttributeValue(null, ATTR_VALUE));
1168                } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
1169                    minimumPasswordMetrics.upperCase = Integer.parseInt(
1170                            parser.getAttributeValue(null, ATTR_VALUE));
1171                } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
1172                    minimumPasswordMetrics.lowerCase = Integer.parseInt(
1173                            parser.getAttributeValue(null, ATTR_VALUE));
1174                } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
1175                    minimumPasswordMetrics.letters = Integer.parseInt(
1176                            parser.getAttributeValue(null, ATTR_VALUE));
1177                } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
1178                    minimumPasswordMetrics.numeric = Integer.parseInt(
1179                            parser.getAttributeValue(null, ATTR_VALUE));
1180                } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
1181                    minimumPasswordMetrics.symbols = Integer.parseInt(
1182                            parser.getAttributeValue(null, ATTR_VALUE));
1183                } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
1184                    minimumPasswordMetrics.nonLetter = Integer.parseInt(
1185                            parser.getAttributeValue(null, ATTR_VALUE));
1186                } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
1187                    maximumTimeToUnlock = Long.parseLong(
1188                            parser.getAttributeValue(null, ATTR_VALUE));
1189                } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
1190                    strongAuthUnlockTimeout = Long.parseLong(
1191                            parser.getAttributeValue(null, ATTR_VALUE));
1192                } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
1193                    maximumFailedPasswordsForWipe = Integer.parseInt(
1194                            parser.getAttributeValue(null, ATTR_VALUE));
1195                } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
1196                    specifiesGlobalProxy = Boolean.parseBoolean(
1197                            parser.getAttributeValue(null, ATTR_VALUE));
1198                } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1199                    globalProxySpec =
1200                        parser.getAttributeValue(null, ATTR_VALUE);
1201                } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1202                    globalProxyExclusionList =
1203                        parser.getAttributeValue(null, ATTR_VALUE);
1204                } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1205                    passwordExpirationTimeout = Long.parseLong(
1206                            parser.getAttributeValue(null, ATTR_VALUE));
1207                } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1208                    passwordExpirationDate = Long.parseLong(
1209                            parser.getAttributeValue(null, ATTR_VALUE));
1210                } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1211                    encryptionRequested = Boolean.parseBoolean(
1212                            parser.getAttributeValue(null, ATTR_VALUE));
1213                } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1214                    testOnlyAdmin = Boolean.parseBoolean(
1215                            parser.getAttributeValue(null, ATTR_VALUE));
1216                } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1217                    disableCamera = Boolean.parseBoolean(
1218                            parser.getAttributeValue(null, ATTR_VALUE));
1219                } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1220                    disableCallerId = Boolean.parseBoolean(
1221                            parser.getAttributeValue(null, ATTR_VALUE));
1222                } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1223                    disableContactsSearch = Boolean.parseBoolean(
1224                            parser.getAttributeValue(null, ATTR_VALUE));
1225                } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1226                    disableBluetoothContactSharing = Boolean.parseBoolean(parser
1227                            .getAttributeValue(null, ATTR_VALUE));
1228                } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1229                    disableScreenCapture = Boolean.parseBoolean(
1230                            parser.getAttributeValue(null, ATTR_VALUE));
1231                } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1232                    requireAutoTime = Boolean.parseBoolean(
1233                            parser.getAttributeValue(null, ATTR_VALUE));
1234                } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1235                    forceEphemeralUsers = Boolean.parseBoolean(
1236                            parser.getAttributeValue(null, ATTR_VALUE));
1237                } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) {
1238                    isNetworkLoggingEnabled = Boolean.parseBoolean(
1239                            parser.getAttributeValue(null, ATTR_VALUE));
1240                    lastNetworkLoggingNotificationTimeMs = Long.parseLong(
1241                            parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION));
1242                    numNetworkLoggingNotifications = Integer.parseInt(
1243                            parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS));
1244                } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1245                    disabledKeyguardFeatures = Integer.parseInt(
1246                            parser.getAttributeValue(null, ATTR_VALUE));
1247                } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1248                    readAttributeValues(
1249                            parser, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1250                } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1251                    trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1252                } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1253                    crossProfileWidgetProviders = new ArrayList<>();
1254                    readAttributeValues(parser, TAG_PROVIDER, crossProfileWidgetProviders);
1255                } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1256                    permittedAccessiblityServices = readPackageList(parser, tag);
1257                } else if (TAG_PERMITTED_IMES.equals(tag)) {
1258                    permittedInputMethods = readPackageList(parser, tag);
1259                } else if (TAG_PERMITTED_NOTIFICATION_LISTENERS.equals(tag)) {
1260                    permittedNotificationListeners = readPackageList(parser, tag);
1261                } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1262                    keepUninstalledPackages = readPackageList(parser, tag);
1263                } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1264                    userRestrictions = UserRestrictionsUtils.readRestrictions(parser);
1265                } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) {
1266                    readAttributeValues(
1267                            parser, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1268                } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1269                    type = parser.next();
1270                    if (type == XmlPullParser.TEXT) {
1271                        shortSupportMessage = parser.getText();
1272                    } else {
1273                        Log.w(LOG_TAG, "Missing text when loading short support message");
1274                    }
1275                } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1276                    type = parser.next();
1277                    if (type == XmlPullParser.TEXT) {
1278                        longSupportMessage = parser.getText();
1279                    } else {
1280                        Log.w(LOG_TAG, "Missing text when loading long support message");
1281                    }
1282                } else if (TAG_PARENT_ADMIN.equals(tag)) {
1283                    Preconditions.checkState(!isParent);
1284
1285                    parentAdmin = new ActiveAdmin(info, /* parent */ true);
1286                    parentAdmin.readFromXml(parser);
1287                } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1288                    organizationColor = Integer.parseInt(
1289                            parser.getAttributeValue(null, ATTR_VALUE));
1290                } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1291                    type = parser.next();
1292                    if (type == XmlPullParser.TEXT) {
1293                        organizationName = parser.getText();
1294                    } else {
1295                        Log.w(LOG_TAG, "Missing text when loading organization name");
1296                    }
1297                } else if (TAG_IS_LOGOUT_ENABLED.equals(tag)) {
1298                    isLogoutEnabled = Boolean.parseBoolean(
1299                            parser.getAttributeValue(null, ATTR_VALUE));
1300                } else {
1301                    Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1302                    XmlUtils.skipCurrentTag(parser);
1303                }
1304            }
1305        }
1306
1307        private List<String> readPackageList(XmlPullParser parser,
1308                String tag) throws XmlPullParserException, IOException {
1309            List<String> result = new ArrayList<String>();
1310            int outerDepth = parser.getDepth();
1311            int outerType;
1312            while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1313                    && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1314                if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1315                    continue;
1316                }
1317                String outerTag = parser.getName();
1318                if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1319                    String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1320                    if (packageName != null) {
1321                        result.add(packageName);
1322                    } else {
1323                        Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1324                    }
1325                } else {
1326                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
1327                }
1328            }
1329            return result;
1330        }
1331
1332        private void readAttributeValues(
1333                XmlPullParser parser, String tag, Collection<String> result)
1334                throws XmlPullParserException, IOException {
1335            result.clear();
1336            int outerDepthDAM = parser.getDepth();
1337            int typeDAM;
1338            while ((typeDAM=parser.next()) != END_DOCUMENT
1339                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1340                if (typeDAM == END_TAG || typeDAM == TEXT) {
1341                    continue;
1342                }
1343                String tagDAM = parser.getName();
1344                if (tag.equals(tagDAM)) {
1345                    result.add(parser.getAttributeValue(null, ATTR_VALUE));
1346                } else {
1347                    Slog.e(LOG_TAG, "Expected tag " + tag +  " but found " + tagDAM);
1348                }
1349            }
1350        }
1351
1352        private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1353                XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1354            int outerDepthDAM = parser.getDepth();
1355            int typeDAM;
1356            final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1357            while ((typeDAM=parser.next()) != END_DOCUMENT
1358                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1359                if (typeDAM == END_TAG || typeDAM == TEXT) {
1360                    continue;
1361                }
1362                String tagDAM = parser.getName();
1363                if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1364                    final String component = parser.getAttributeValue(null, ATTR_VALUE);
1365                    final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1366                    result.put(component, trustAgentInfo);
1367                } else {
1368                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1369                }
1370            }
1371            return result;
1372        }
1373
1374        private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1375                throws XmlPullParserException, IOException  {
1376            int outerDepthDAM = parser.getDepth();
1377            int typeDAM;
1378            TrustAgentInfo result = new TrustAgentInfo(null);
1379            while ((typeDAM=parser.next()) != END_DOCUMENT
1380                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1381                if (typeDAM == END_TAG || typeDAM == TEXT) {
1382                    continue;
1383                }
1384                String tagDAM = parser.getName();
1385                if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1386                    result.options = PersistableBundle.restoreFromXml(parser);
1387                } else {
1388                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1389                }
1390            }
1391            return result;
1392        }
1393
1394        boolean hasUserRestrictions() {
1395            return userRestrictions != null && userRestrictions.size() > 0;
1396        }
1397
1398        Bundle ensureUserRestrictions() {
1399            if (userRestrictions == null) {
1400                userRestrictions = new Bundle();
1401            }
1402            return userRestrictions;
1403        }
1404
1405        void dump(String prefix, PrintWriter pw) {
1406            pw.print(prefix); pw.print("uid="); pw.println(getUid());
1407            pw.print(prefix); pw.print("testOnlyAdmin=");
1408            pw.println(testOnlyAdmin);
1409            pw.print(prefix); pw.println("policies:");
1410            ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1411            if (pols != null) {
1412                for (int i=0; i<pols.size(); i++) {
1413                    pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
1414                }
1415            }
1416            pw.print(prefix); pw.print("passwordQuality=0x");
1417                    pw.println(Integer.toHexString(minimumPasswordMetrics.quality));
1418            pw.print(prefix); pw.print("minimumPasswordLength=");
1419                    pw.println(minimumPasswordMetrics.length);
1420            pw.print(prefix); pw.print("passwordHistoryLength=");
1421                    pw.println(passwordHistoryLength);
1422            pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1423                    pw.println(minimumPasswordMetrics.upperCase);
1424            pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1425                    pw.println(minimumPasswordMetrics.lowerCase);
1426            pw.print(prefix); pw.print("minimumPasswordLetters=");
1427                    pw.println(minimumPasswordMetrics.letters);
1428            pw.print(prefix); pw.print("minimumPasswordNumeric=");
1429                    pw.println(minimumPasswordMetrics.numeric);
1430            pw.print(prefix); pw.print("minimumPasswordSymbols=");
1431                    pw.println(minimumPasswordMetrics.symbols);
1432            pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1433                    pw.println(minimumPasswordMetrics.nonLetter);
1434            pw.print(prefix); pw.print("maximumTimeToUnlock=");
1435                    pw.println(maximumTimeToUnlock);
1436            pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1437                    pw.println(strongAuthUnlockTimeout);
1438            pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1439                    pw.println(maximumFailedPasswordsForWipe);
1440            pw.print(prefix); pw.print("specifiesGlobalProxy=");
1441                    pw.println(specifiesGlobalProxy);
1442            pw.print(prefix); pw.print("passwordExpirationTimeout=");
1443                    pw.println(passwordExpirationTimeout);
1444            pw.print(prefix); pw.print("passwordExpirationDate=");
1445                    pw.println(passwordExpirationDate);
1446            if (globalProxySpec != null) {
1447                pw.print(prefix); pw.print("globalProxySpec=");
1448                        pw.println(globalProxySpec);
1449            }
1450            if (globalProxyExclusionList != null) {
1451                pw.print(prefix); pw.print("globalProxyEclusionList=");
1452                        pw.println(globalProxyExclusionList);
1453            }
1454            pw.print(prefix); pw.print("encryptionRequested=");
1455                    pw.println(encryptionRequested);
1456            pw.print(prefix); pw.print("disableCamera=");
1457                    pw.println(disableCamera);
1458            pw.print(prefix); pw.print("disableCallerId=");
1459                    pw.println(disableCallerId);
1460            pw.print(prefix); pw.print("disableContactsSearch=");
1461                    pw.println(disableContactsSearch);
1462            pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1463                    pw.println(disableBluetoothContactSharing);
1464            pw.print(prefix); pw.print("disableScreenCapture=");
1465                    pw.println(disableScreenCapture);
1466            pw.print(prefix); pw.print("requireAutoTime=");
1467                    pw.println(requireAutoTime);
1468            pw.print(prefix); pw.print("forceEphemeralUsers=");
1469                    pw.println(forceEphemeralUsers);
1470            pw.print(prefix); pw.print("isNetworkLoggingEnabled=");
1471                    pw.println(isNetworkLoggingEnabled);
1472            pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1473                    pw.println(disabledKeyguardFeatures);
1474            pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1475                    pw.println(crossProfileWidgetProviders);
1476            if (permittedAccessiblityServices != null) {
1477                pw.print(prefix); pw.print("permittedAccessibilityServices=");
1478                    pw.println(permittedAccessiblityServices);
1479            }
1480            if (permittedInputMethods != null) {
1481                pw.print(prefix); pw.print("permittedInputMethods=");
1482                    pw.println(permittedInputMethods);
1483            }
1484            if (permittedNotificationListeners != null) {
1485                pw.print(prefix); pw.print("permittedNotificationListeners=");
1486                pw.println(permittedNotificationListeners);
1487            }
1488            if (keepUninstalledPackages != null) {
1489                pw.print(prefix); pw.print("keepUninstalledPackages=");
1490                    pw.println(keepUninstalledPackages);
1491            }
1492            pw.print(prefix); pw.print("organizationColor=");
1493                    pw.println(organizationColor);
1494            if (organizationName != null) {
1495                pw.print(prefix); pw.print("organizationName=");
1496                    pw.println(organizationName);
1497            }
1498            pw.print(prefix); pw.println("userRestrictions:");
1499            UserRestrictionsUtils.dumpRestrictions(pw, prefix + "  ", userRestrictions);
1500            pw.print(prefix); pw.print("defaultEnabledRestrictionsAlreadySet=");
1501                    pw.println(defaultEnabledRestrictionsAlreadySet);
1502            pw.print(prefix); pw.print("isParent=");
1503                    pw.println(isParent);
1504            if (parentAdmin != null) {
1505                pw.print(prefix);  pw.println("parentAdmin:");
1506                parentAdmin.dump(prefix + "  ", pw);
1507            }
1508        }
1509    }
1510
1511    private void handlePackagesChanged(@Nullable String packageName, int userHandle) {
1512        boolean removedAdmin = false;
1513        if (VERBOSE_LOG) {
1514            Slog.d(LOG_TAG, "Handling package changes package " + packageName
1515                    + " for user " + userHandle);
1516        }
1517        DevicePolicyData policy = getUserData(userHandle);
1518        synchronized (this) {
1519            for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1520                ActiveAdmin aa = policy.mAdminList.get(i);
1521                try {
1522                    // If we're checking all packages or if the specific one we're checking matches,
1523                    // then check if the package and receiver still exist.
1524                    final String adminPackage = aa.info.getPackageName();
1525                    if (packageName == null || packageName.equals(adminPackage)) {
1526                        if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1527                                || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1528                                PackageManager.MATCH_DIRECT_BOOT_AWARE
1529                                        | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1530                                userHandle) == null) {
1531                            removedAdmin = true;
1532                            policy.mAdminList.remove(i);
1533                            policy.mAdminMap.remove(aa.info.getComponent());
1534                        }
1535                    }
1536                } catch (RemoteException re) {
1537                    // Shouldn't happen.
1538                }
1539            }
1540            if (removedAdmin) {
1541                validatePasswordOwnerLocked(policy);
1542            }
1543
1544            boolean removedDelegate = false;
1545
1546            // Check if a delegate was removed.
1547            for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
1548                final String delegatePackage = policy.mDelegationMap.keyAt(i);
1549                if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
1550                    policy.mDelegationMap.removeAt(i);
1551                    removedDelegate = true;
1552                }
1553            }
1554
1555            // If it's an owner package, we may need to refresh the bound connection.
1556            final ComponentName owner = getOwnerComponent(userHandle);
1557            if ((packageName != null) && (owner != null)
1558                    && (owner.getPackageName().equals(packageName))) {
1559                startOwnerService(userHandle, "package-broadcast");
1560            }
1561
1562            // Persist updates if the removed package was an admin or delegate.
1563            if (removedAdmin || removedDelegate) {
1564                saveSettingsLocked(policy.mUserHandle);
1565            }
1566        }
1567        if (removedAdmin) {
1568            // The removed admin might have disabled camera, so update user restrictions.
1569            pushUserRestrictions(userHandle);
1570        }
1571    }
1572
1573    private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1574        try {
1575            return targetPackage != null
1576                    && (changedPackage == null || changedPackage.equals(targetPackage))
1577                    && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1578        } catch (RemoteException e) {
1579            // Shouldn't happen
1580        }
1581
1582        return false;
1583    }
1584
1585    /**
1586     * Unit test will subclass it to inject mocks.
1587     */
1588    @VisibleForTesting
1589    static class Injector {
1590
1591        public final Context mContext;
1592
1593        Injector(Context context) {
1594            mContext = context;
1595        }
1596
1597        public boolean hasFeature() {
1598            return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1599        }
1600
1601        Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
1602            final String packageName = mContext.getPackageName();
1603            return mContext.createPackageContextAsUser(packageName, 0, user);
1604        }
1605
1606        Resources getResources() {
1607            return mContext.getResources();
1608        }
1609
1610        Owners newOwners() {
1611            return new Owners(getUserManager(), getUserManagerInternal(),
1612                    getPackageManagerInternal());
1613        }
1614
1615        UserManager getUserManager() {
1616            return UserManager.get(mContext);
1617        }
1618
1619        UserManagerInternal getUserManagerInternal() {
1620            return LocalServices.getService(UserManagerInternal.class);
1621        }
1622
1623        PackageManagerInternal getPackageManagerInternal() {
1624            return LocalServices.getService(PackageManagerInternal.class);
1625        }
1626
1627        NotificationManager getNotificationManager() {
1628            return mContext.getSystemService(NotificationManager.class);
1629        }
1630
1631        IIpConnectivityMetrics getIIpConnectivityMetrics() {
1632            return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1633                ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1634        }
1635
1636        PackageManager getPackageManager() {
1637            return mContext.getPackageManager();
1638        }
1639
1640        PowerManagerInternal getPowerManagerInternal() {
1641            return LocalServices.getService(PowerManagerInternal.class);
1642        }
1643
1644        TelephonyManager getTelephonyManager() {
1645            return TelephonyManager.from(mContext);
1646        }
1647
1648        TrustManager getTrustManager() {
1649            return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1650        }
1651
1652        AlarmManager getAlarmManager() {
1653            return (AlarmManager) mContext.getSystemService(AlarmManager.class);
1654        }
1655
1656        IWindowManager getIWindowManager() {
1657            return IWindowManager.Stub
1658                    .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1659        }
1660
1661        IActivityManager getIActivityManager() {
1662            return ActivityManager.getService();
1663        }
1664
1665        IPackageManager getIPackageManager() {
1666            return AppGlobals.getPackageManager();
1667        }
1668
1669        IBackupManager getIBackupManager() {
1670            return IBackupManager.Stub.asInterface(
1671                    ServiceManager.getService(Context.BACKUP_SERVICE));
1672        }
1673
1674        IAudioService getIAudioService() {
1675            return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1676        }
1677
1678        boolean isBuildDebuggable() {
1679            return Build.IS_DEBUGGABLE;
1680        }
1681
1682        LockPatternUtils newLockPatternUtils() {
1683            return new LockPatternUtils(mContext);
1684        }
1685
1686        boolean storageManagerIsFileBasedEncryptionEnabled() {
1687            return StorageManager.isFileEncryptedNativeOnly();
1688        }
1689
1690        boolean storageManagerIsNonDefaultBlockEncrypted() {
1691            long identity = Binder.clearCallingIdentity();
1692            try {
1693                return StorageManager.isNonDefaultBlockEncrypted();
1694            } finally {
1695                Binder.restoreCallingIdentity(identity);
1696            }
1697        }
1698
1699        boolean storageManagerIsEncrypted() {
1700            return StorageManager.isEncrypted();
1701        }
1702
1703        boolean storageManagerIsEncryptable() {
1704            return StorageManager.isEncryptable();
1705        }
1706
1707        Looper getMyLooper() {
1708            return Looper.myLooper();
1709        }
1710
1711        WifiManager getWifiManager() {
1712            return mContext.getSystemService(WifiManager.class);
1713        }
1714
1715        long binderClearCallingIdentity() {
1716            return Binder.clearCallingIdentity();
1717        }
1718
1719        void binderRestoreCallingIdentity(long token) {
1720            Binder.restoreCallingIdentity(token);
1721        }
1722
1723        int binderGetCallingUid() {
1724            return Binder.getCallingUid();
1725        }
1726
1727        int binderGetCallingPid() {
1728            return Binder.getCallingPid();
1729        }
1730
1731        UserHandle binderGetCallingUserHandle() {
1732            return Binder.getCallingUserHandle();
1733        }
1734
1735        boolean binderIsCallingUidMyUid() {
1736            return getCallingUid() == Process.myUid();
1737        }
1738
1739        void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) {
1740             Binder.withCleanCallingIdentity(action);
1741        }
1742
1743        final int userHandleGetCallingUserId() {
1744            return UserHandle.getUserId(binderGetCallingUid());
1745        }
1746
1747        File environmentGetUserSystemDirectory(int userId) {
1748            return Environment.getUserSystemDirectory(userId);
1749        }
1750
1751        void powerManagerGoToSleep(long time, int reason, int flags) {
1752            mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1753        }
1754
1755        void powerManagerReboot(String reason) {
1756            mContext.getSystemService(PowerManager.class).reboot(reason);
1757        }
1758
1759        void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force,
1760                boolean wipeEuicc) throws IOException {
1761            RecoverySystem.rebootWipeUserData(mContext, shutdown, reason, force, wipeEuicc);
1762        }
1763
1764        boolean systemPropertiesGetBoolean(String key, boolean def) {
1765            return SystemProperties.getBoolean(key, def);
1766        }
1767
1768        long systemPropertiesGetLong(String key, long def) {
1769            return SystemProperties.getLong(key, def);
1770        }
1771
1772        String systemPropertiesGet(String key, String def) {
1773            return SystemProperties.get(key, def);
1774        }
1775
1776        String systemPropertiesGet(String key) {
1777            return SystemProperties.get(key);
1778        }
1779
1780        void systemPropertiesSet(String key, String value) {
1781            SystemProperties.set(key, value);
1782        }
1783
1784        boolean userManagerIsSplitSystemUser() {
1785            return UserManager.isSplitSystemUser();
1786        }
1787
1788        String getDevicePolicyFilePathForSystemUser() {
1789            return "/data/system/";
1790        }
1791
1792        PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode,
1793                @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
1794            return PendingIntent.getActivityAsUser(
1795                    context, requestCode, intent, flags, options, user);
1796        }
1797
1798        void registerContentObserver(Uri uri, boolean notifyForDescendents,
1799                ContentObserver observer, int userHandle) {
1800            mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1801                    observer, userHandle);
1802        }
1803
1804        int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1805            return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1806                    name, def, userHandle);
1807        }
1808
1809        String settingsSecureGetStringForUser(String name, int userHandle) {
1810            return Settings.Secure.getStringForUser(mContext.getContentResolver(), name,
1811                    userHandle);
1812        }
1813
1814        void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1815            Settings.Secure.putIntForUser(mContext.getContentResolver(),
1816                    name, value, userHandle);
1817        }
1818
1819        void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1820            Settings.Secure.putStringForUser(mContext.getContentResolver(),
1821                    name, value, userHandle);
1822        }
1823
1824        void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1825            Settings.Global.putStringForUser(mContext.getContentResolver(),
1826                    name, value, userHandle);
1827        }
1828
1829        void settingsSecurePutInt(String name, int value) {
1830            Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1831        }
1832
1833        int settingsGlobalGetInt(String name, int def) {
1834            return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1835        }
1836
1837        String settingsGlobalGetString(String name) {
1838            return Settings.Global.getString(mContext.getContentResolver(), name);
1839        }
1840
1841        void settingsGlobalPutInt(String name, int value) {
1842            Settings.Global.putInt(mContext.getContentResolver(), name, value);
1843        }
1844
1845        void settingsSecurePutString(String name, String value) {
1846            Settings.Secure.putString(mContext.getContentResolver(), name, value);
1847        }
1848
1849        void settingsGlobalPutString(String name, String value) {
1850            Settings.Global.putString(mContext.getContentResolver(), name, value);
1851        }
1852
1853        void settingsSystemPutString(String name, String value) {
1854            Settings.System.putString(mContext.getContentResolver(), name, value);
1855        }
1856
1857        void securityLogSetLoggingEnabledProperty(boolean enabled) {
1858            SecurityLog.setLoggingEnabledProperty(enabled);
1859        }
1860
1861        boolean securityLogGetLoggingEnabledProperty() {
1862            return SecurityLog.getLoggingEnabledProperty();
1863        }
1864
1865        boolean securityLogIsLoggingEnabled() {
1866            return SecurityLog.isLoggingEnabled();
1867        }
1868
1869        KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException {
1870            return KeyChain.bindAsUser(mContext, user);
1871        }
1872    }
1873
1874    /**
1875     * Instantiates the service.
1876     */
1877    public DevicePolicyManagerService(Context context) {
1878        this(new Injector(context));
1879    }
1880
1881    @VisibleForTesting
1882    DevicePolicyManagerService(Injector injector) {
1883        mInjector = injector;
1884        mContext = Preconditions.checkNotNull(injector.mContext);
1885        mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1886        mConstants = DevicePolicyConstants.loadFromString(
1887                mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS));
1888
1889        mOwners = Preconditions.checkNotNull(injector.newOwners());
1890
1891        mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1892        mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1893        mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1894        mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1895
1896        mLocalService = new LocalService();
1897        mLockPatternUtils = injector.newLockPatternUtils();
1898
1899        // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false?
1900        mSecurityLogMonitor = new SecurityLogMonitor(this);
1901
1902        mHasFeature = mInjector.hasFeature();
1903        mIsWatch = mInjector.getPackageManager()
1904                .hasSystemFeature(PackageManager.FEATURE_WATCH);
1905        mBackgroundHandler = BackgroundThread.getHandler();
1906
1907        // Needed when mHasFeature == false, because it controls the certificate warning text.
1908        mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler);
1909
1910        mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants);
1911
1912        mOverlayPackagesProvider = new OverlayPackagesProvider(mContext);
1913
1914        if (!mHasFeature) {
1915            // Skip the rest of the initialization
1916            return;
1917        }
1918
1919        IntentFilter filter = new IntentFilter();
1920        filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1921        filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1922        filter.addAction(Intent.ACTION_USER_ADDED);
1923        filter.addAction(Intent.ACTION_USER_REMOVED);
1924        filter.addAction(Intent.ACTION_USER_STARTED);
1925        filter.addAction(Intent.ACTION_USER_UNLOCKED);
1926        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1927        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1928        filter = new IntentFilter();
1929        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1930        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1931        filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1932        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1933        filter.addDataScheme("package");
1934        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1935        filter = new IntentFilter();
1936        filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1937        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1938
1939        LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1940
1941        mSetupContentObserver = new SetupContentObserver(mHandler);
1942    }
1943
1944    /**
1945     * Creates and loads the policy data from xml.
1946     * @param userHandle the user for whom to load the policy data
1947     * @return
1948     */
1949    @NonNull
1950    DevicePolicyData getUserData(int userHandle) {
1951        synchronized (this) {
1952            DevicePolicyData policy = mUserData.get(userHandle);
1953            if (policy == null) {
1954                policy = new DevicePolicyData(userHandle);
1955                mUserData.append(userHandle, policy);
1956                loadSettingsLocked(policy, userHandle);
1957            }
1958            return policy;
1959        }
1960    }
1961
1962    /**
1963     * Creates and loads the policy data from xml for data that is shared between
1964     * various profiles of a user. In contrast to {@link #getUserData(int)}
1965     * it allows access to data of users other than the calling user.
1966     *
1967     * This function should only be used for shared data, e.g. everything regarding
1968     * passwords and should be removed once multiple screen locks are present.
1969     * @param userHandle the user for whom to load the policy data
1970     * @return
1971     */
1972    DevicePolicyData getUserDataUnchecked(int userHandle) {
1973        long ident = mInjector.binderClearCallingIdentity();
1974        try {
1975            return getUserData(userHandle);
1976        } finally {
1977            mInjector.binderRestoreCallingIdentity(ident);
1978        }
1979    }
1980
1981    void removeUserData(int userHandle) {
1982        synchronized (this) {
1983            if (userHandle == UserHandle.USER_SYSTEM) {
1984                Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1985                return;
1986            }
1987            mOwners.removeProfileOwner(userHandle);
1988            mOwners.writeProfileOwner(userHandle);
1989
1990            DevicePolicyData policy = mUserData.get(userHandle);
1991            if (policy != null) {
1992                mUserData.remove(userHandle);
1993            }
1994            File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1995                    DEVICE_POLICIES_XML);
1996            policyFile.delete();
1997            Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1998        }
1999        updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
2000    }
2001
2002    void loadOwners() {
2003        synchronized (this) {
2004            mOwners.load();
2005            setDeviceOwnerSystemPropertyLocked();
2006            findOwnerComponentIfNecessaryLocked();
2007            migrateUserRestrictionsIfNecessaryLocked();
2008            maybeSetDefaultDeviceOwnerUserRestrictionsLocked();
2009
2010            // TODO PO may not have a class name either due to b/17652534.  Address that too.
2011
2012            updateDeviceOwnerLocked();
2013        }
2014    }
2015
2016    /** Apply default restrictions that haven't been applied to device owners yet. */
2017    private void maybeSetDefaultDeviceOwnerUserRestrictionsLocked() {
2018        final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2019        if (deviceOwner != null) {
2020            maybeSetDefaultRestrictionsForAdminLocked(mOwners.getDeviceOwnerUserId(),
2021                    deviceOwner, UserRestrictionsUtils.getDefaultEnabledForDeviceOwner());
2022        }
2023    }
2024
2025    /** Apply default restrictions that haven't been applied to profile owners yet. */
2026    private void maybeSetDefaultProfileOwnerUserRestrictions() {
2027        synchronized (this) {
2028            for (final int userId : mOwners.getProfileOwnerKeys()) {
2029                final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
2030                // The following restrictions used to be applied to managed profiles by different
2031                // means (via Settings or by disabling components). Now they are proper user
2032                // restrictions so we apply them to managed profile owners. Non-managed secondary
2033                // users didn't have those restrictions so we skip them to keep existing behavior.
2034                if (profileOwner == null || !mUserManager.isManagedProfile(userId)) {
2035                    continue;
2036                }
2037                maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner,
2038                        UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
2039                ensureUnknownSourcesRestrictionForProfileOwnerLocked(
2040                        userId, profileOwner, false /* newOwner */);
2041            }
2042        }
2043    }
2044
2045    /**
2046     * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the
2047     * set of restrictions for this profile owner.
2048     */
2049    private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId,
2050            ActiveAdmin profileOwner, boolean newOwner) {
2051        if (newOwner || mInjector.settingsSecureGetIntForUser(
2052                Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
2053            profileOwner.ensureUserRestrictions().putBoolean(
2054                    UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
2055            saveUserRestrictionsLocked(userId);
2056            mInjector.settingsSecurePutIntForUser(
2057                    Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
2058        }
2059    }
2060
2061    /**
2062     * Apply default restrictions that haven't been applied to a given admin yet.
2063     */
2064    private void maybeSetDefaultRestrictionsForAdminLocked(
2065            int userId, ActiveAdmin admin, Set<String> defaultRestrictions) {
2066        if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
2067            return; // The same set of default restrictions has been already applied.
2068        }
2069        Slog.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId);
2070
2071        if (VERBOSE_LOG) {
2072            Slog.d(LOG_TAG,"Default enabled restrictions: "
2073                    + defaultRestrictions
2074                    + ". Restrictions already enabled: "
2075                    + admin.defaultEnabledRestrictionsAlreadySet);
2076        }
2077
2078        final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions);
2079        restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet);
2080        if (!restrictionsToSet.isEmpty()) {
2081            for (final String restriction : restrictionsToSet) {
2082                admin.ensureUserRestrictions().putBoolean(restriction, true);
2083            }
2084            admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet);
2085            Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet);
2086            saveUserRestrictionsLocked(userId);
2087        }
2088    }
2089
2090    private void setDeviceOwnerSystemPropertyLocked() {
2091        final boolean deviceProvisioned =
2092                mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0;
2093        final boolean hasDeviceOwner = mOwners.hasDeviceOwner();
2094        // If the device is not provisioned and there is currently no device owner, do not set the
2095        // read-only system property yet, since Device owner may still be provisioned.
2096        if (!hasDeviceOwner && !deviceProvisioned) {
2097            return;
2098        }
2099        // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
2100        // always false at this point.
2101        if (StorageManager.inCryptKeeperBounce()) {
2102            return;
2103        }
2104
2105        if (!mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT, "").isEmpty()) {
2106            Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
2107        } else {
2108            final String value = Boolean.toString(hasDeviceOwner);
2109            mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, value);
2110            Slog.i(LOG_TAG, "Set ro.device_owner property to " + value);
2111
2112            if (hasDeviceOwner && mInjector.securityLogGetLoggingEnabledProperty()) {
2113                mSecurityLogMonitor.start();
2114                maybePauseDeviceWideLoggingLocked();
2115            }
2116        }
2117    }
2118
2119    private void findOwnerComponentIfNecessaryLocked() {
2120        if (!mOwners.hasDeviceOwner()) {
2121            return;
2122        }
2123        final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
2124
2125        if (!TextUtils.isEmpty(doComponentName.getClassName())) {
2126            return; // Already a full component name.
2127        }
2128
2129        final ComponentName doComponent = findAdminComponentWithPackageLocked(
2130                doComponentName.getPackageName(),
2131                mOwners.getDeviceOwnerUserId());
2132        if (doComponent == null) {
2133            Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
2134        } else {
2135            mOwners.setDeviceOwnerWithRestrictionsMigrated(
2136                    doComponent,
2137                    mOwners.getDeviceOwnerName(),
2138                    mOwners.getDeviceOwnerUserId(),
2139                    !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
2140            mOwners.writeDeviceOwner();
2141            if (VERBOSE_LOG) {
2142                Log.v(LOG_TAG, "Device owner component filled in");
2143            }
2144        }
2145    }
2146
2147    /**
2148     * We didn't use to persist user restrictions for each owners but only persisted in user
2149     * manager.
2150     */
2151    private void migrateUserRestrictionsIfNecessaryLocked() {
2152        boolean migrated = false;
2153        // Migrate for the DO.  Basically all restrictions should be considered to be set by DO,
2154        // except for the "system controlled" ones.
2155        if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
2156            if (VERBOSE_LOG) {
2157                Log.v(LOG_TAG, "Migrating DO user restrictions");
2158            }
2159            migrated = true;
2160
2161            // Migrate user 0 restrictions to DO.
2162            final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
2163
2164            migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
2165                    /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
2166
2167            // Push DO user restrictions to user manager.
2168            pushUserRestrictions(UserHandle.USER_SYSTEM);
2169
2170            mOwners.setDeviceOwnerUserRestrictionsMigrated();
2171        }
2172
2173        // Migrate for POs.
2174
2175        // The following restrictions can be set on secondary users by the device owner, so we
2176        // assume they're not from the PO.
2177        final Set<String> secondaryUserExceptionList = Sets.newArraySet(
2178                UserManager.DISALLOW_OUTGOING_CALLS,
2179                UserManager.DISALLOW_SMS);
2180
2181        for (UserInfo ui : mUserManager.getUsers()) {
2182            final int userId = ui.id;
2183            if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
2184                if (VERBOSE_LOG) {
2185                    Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
2186                }
2187                migrated = true;
2188
2189                final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
2190
2191                final Set<String> exceptionList =
2192                        (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
2193
2194                migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
2195                        exceptionList, /* isDeviceOwner =*/ false);
2196
2197                // Note if a secondary user has no PO but has a DA that disables camera, we
2198                // don't get here and won't push the camera user restriction to UserManager
2199                // here.  That's okay because we'll push user restrictions anyway when a user
2200                // starts.  But we still do it because we want to let user manager persist
2201                // upon migration.
2202                pushUserRestrictions(userId);
2203
2204                mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
2205            }
2206        }
2207        if (VERBOSE_LOG && migrated) {
2208            Log.v(LOG_TAG, "User restrictions migrated.");
2209        }
2210    }
2211
2212    private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
2213            Set<String> exceptionList, boolean isDeviceOwner) {
2214        final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
2215                user.getIdentifier());
2216
2217        final Bundle newBaseRestrictions = new Bundle();
2218        final Bundle newOwnerRestrictions = new Bundle();
2219
2220        for (String key : origRestrictions.keySet()) {
2221            if (!origRestrictions.getBoolean(key)) {
2222                continue;
2223            }
2224            final boolean canOwnerChange = isDeviceOwner
2225                    ? UserRestrictionsUtils.canDeviceOwnerChange(key)
2226                    : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
2227
2228            if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
2229                newBaseRestrictions.putBoolean(key, true);
2230            } else {
2231                newOwnerRestrictions.putBoolean(key, true);
2232            }
2233        }
2234
2235        if (VERBOSE_LOG) {
2236            Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
2237            Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
2238            Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
2239        }
2240        mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
2241                newBaseRestrictions);
2242
2243        if (admin != null) {
2244            admin.ensureUserRestrictions().clear();
2245            admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
2246        } else {
2247            Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
2248        }
2249        saveSettingsLocked(user.getIdentifier());
2250    }
2251
2252    private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
2253        final DevicePolicyData policy = getUserData(userId);
2254        final int n = policy.mAdminList.size();
2255        ComponentName found = null;
2256        int nFound = 0;
2257        for (int i = 0; i < n; i++) {
2258            final ActiveAdmin admin = policy.mAdminList.get(i);
2259            if (packageName.equals(admin.info.getPackageName())) {
2260                // Found!
2261                if (nFound == 0) {
2262                    found = admin.info.getComponent();
2263                }
2264                nFound++;
2265            }
2266        }
2267        if (nFound > 1) {
2268            Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
2269        }
2270        return found;
2271    }
2272
2273    /**
2274     * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
2275     * reminders.  Clears alarm if no expirations are configured.
2276     */
2277    private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
2278        final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
2279        final long now = System.currentTimeMillis();
2280        final long timeToExpire = expiration - now;
2281        final long alarmTime;
2282        if (expiration == 0) {
2283            // No expirations are currently configured:  Cancel alarm.
2284            alarmTime = 0;
2285        } else if (timeToExpire <= 0) {
2286            // The password has already expired:  Repeat every 24 hours.
2287            alarmTime = now + MS_PER_DAY;
2288        } else {
2289            // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
2290            // the expiration time.
2291            long alarmInterval = timeToExpire % MS_PER_DAY;
2292            if (alarmInterval == 0) {
2293                alarmInterval = MS_PER_DAY;
2294            }
2295            alarmTime = now + alarmInterval;
2296        }
2297
2298        long token = mInjector.binderClearCallingIdentity();
2299        try {
2300            int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
2301            AlarmManager am = mInjector.getAlarmManager();
2302            PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2303                    new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2304                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
2305                    UserHandle.of(affectedUserHandle));
2306            am.cancel(pi);
2307            if (alarmTime != 0) {
2308                am.set(AlarmManager.RTC, alarmTime, pi);
2309            }
2310        } finally {
2311            mInjector.binderRestoreCallingIdentity(token);
2312        }
2313    }
2314
2315    ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2316        ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2317        if (admin != null
2318                && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2319                && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2320            return admin;
2321        }
2322        return null;
2323    }
2324
2325    ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2326        if (parent) {
2327            enforceManagedProfile(userHandle, "call APIs on the parent profile");
2328        }
2329        ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2330        if (admin != null && parent) {
2331            admin = admin.getParentActiveAdmin();
2332        }
2333        return admin;
2334    }
2335
2336    ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2337            throws SecurityException {
2338        final int callingUid = mInjector.binderGetCallingUid();
2339
2340        ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
2341        if (result != null) {
2342            return result;
2343        }
2344
2345        if (who != null) {
2346            final int userId = UserHandle.getUserId(callingUid);
2347            final DevicePolicyData policy = getUserData(userId);
2348            ActiveAdmin admin = policy.mAdminMap.get(who);
2349            if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2350                throw new SecurityException("Admin " + admin.info.getComponent()
2351                         + " does not own the device");
2352            }
2353            if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2354                throw new SecurityException("Admin " + admin.info.getComponent()
2355                        + " does not own the profile");
2356            }
2357            throw new SecurityException("Admin " + admin.info.getComponent()
2358                    + " did not specify uses-policy for: "
2359                    + admin.info.getTagForPolicy(reqPolicy));
2360        } else {
2361            throw new SecurityException("No active admin owned by uid "
2362                    + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
2363        }
2364    }
2365
2366    ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2367            throws SecurityException {
2368        if (parent) {
2369            enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2370                    "call APIs on the parent profile");
2371        }
2372        ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2373        return parent ? admin.getParentActiveAdmin() : admin;
2374    }
2375    /**
2376     * Find the admin for the component and userId bit of the uid, then check
2377     * the admin's uid matches the uid.
2378     */
2379    private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2380        final int userId = UserHandle.getUserId(uid);
2381        final DevicePolicyData policy = getUserData(userId);
2382        ActiveAdmin admin = policy.mAdminMap.get(who);
2383        if (admin == null) {
2384            throw new SecurityException("No active admin " + who);
2385        }
2386        if (admin.getUid() != uid) {
2387            throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2388        }
2389        return admin;
2390    }
2391
2392    private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2393            int uid) {
2394        // Try to find an admin which can use reqPolicy
2395        final int userId = UserHandle.getUserId(uid);
2396        final DevicePolicyData policy = getUserData(userId);
2397        if (who != null) {
2398            ActiveAdmin admin = policy.mAdminMap.get(who);
2399            if (admin == null) {
2400                throw new SecurityException("No active admin " + who);
2401            }
2402            if (admin.getUid() != uid) {
2403                throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2404            }
2405            if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2406                return admin;
2407            }
2408        } else {
2409            for (ActiveAdmin admin : policy.mAdminList) {
2410                if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2411                        userId)) {
2412                    return admin;
2413                }
2414            }
2415        }
2416
2417        return null;
2418    }
2419
2420    @VisibleForTesting
2421    boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2422            int userId) {
2423        final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2424        final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2425
2426        if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2427            return ownsDevice;
2428        } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2429            // DO always has the PO power.
2430            return ownsDevice || ownsProfile;
2431        } else {
2432            return admin.info.usesPolicy(reqPolicy);
2433        }
2434    }
2435
2436    void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2437        sendAdminCommandLocked(admin, action, null);
2438    }
2439
2440    void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2441        sendAdminCommandLocked(admin, action, null, result);
2442    }
2443
2444    void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2445            BroadcastReceiver result) {
2446        sendAdminCommandLocked(admin, action, adminExtras, result, false);
2447    }
2448
2449    /**
2450     * Send an update to one specific admin, get notified when that admin returns a result.
2451     *
2452     * @return whether the broadcast was successfully sent
2453     */
2454    boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2455            BroadcastReceiver result, boolean inForeground) {
2456        Intent intent = new Intent(action);
2457        intent.setComponent(admin.info.getComponent());
2458        if (UserManager.isDeviceInDemoMode(mContext)) {
2459            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2460        }
2461        if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2462            intent.putExtra("expiration", admin.passwordExpirationDate);
2463        }
2464        if (inForeground) {
2465            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2466        }
2467        if (adminExtras != null) {
2468            intent.putExtras(adminExtras);
2469        }
2470        if (mInjector.getPackageManager().queryBroadcastReceiversAsUser(
2471                intent,
2472                PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2473                admin.getUserHandle()).isEmpty()) {
2474            return false;
2475        }
2476        if (result != null) {
2477            mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2478                    null, result, mHandler, Activity.RESULT_OK, null, null);
2479        } else {
2480            mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2481        }
2482        return true;
2483    }
2484
2485    /**
2486     * Send an update to all admins of a user that enforce a specified policy.
2487     */
2488    void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) {
2489        final DevicePolicyData policy = getUserData(userHandle);
2490        final int count = policy.mAdminList.size();
2491        for (int i = 0; i < count; i++) {
2492            final ActiveAdmin admin = policy.mAdminList.get(i);
2493            if (admin.info.usesPolicy(reqPolicy)) {
2494                sendAdminCommandLocked(admin, action, adminExtras, null);
2495            }
2496        }
2497    }
2498
2499    /**
2500     * Send an update intent to all admins of a user and its profiles. Only send to admins that
2501     * enforce a specified policy.
2502     */
2503    private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2504            int userHandle, Bundle adminExtras) {
2505        int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2506        for (int profileId : profileIds) {
2507            sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras);
2508        }
2509    }
2510
2511    /**
2512     * Sends a broadcast to each profile that share the password unlock with the given user id.
2513     */
2514    private void sendAdminCommandForLockscreenPoliciesLocked(
2515            String action, int reqPolicy, int userHandle) {
2516        final Bundle extras = new Bundle();
2517        extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
2518        if (isSeparateProfileChallengeEnabled(userHandle)) {
2519            sendAdminCommandLocked(action, reqPolicy, userHandle, extras);
2520        } else {
2521            sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras);
2522        }
2523    }
2524
2525    void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2526        final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2527        DevicePolicyData policy = getUserData(userHandle);
2528        if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2529            policy.mRemovingAdmins.add(adminReceiver);
2530            sendAdminCommandLocked(admin,
2531                    DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2532                    new BroadcastReceiver() {
2533                        @Override
2534                        public void onReceive(Context context, Intent intent) {
2535                            removeAdminArtifacts(adminReceiver, userHandle);
2536                            removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2537                        }
2538                    });
2539        }
2540    }
2541
2542
2543    public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2544            boolean throwForMissiongPermission) {
2545        if (!mHasFeature) {
2546            return null;
2547        }
2548        enforceFullCrossUsersPermission(userHandle);
2549        ActivityInfo ai = null;
2550        try {
2551            ai = mIPackageManager.getReceiverInfo(adminName,
2552                    PackageManager.GET_META_DATA |
2553                    PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2554                    PackageManager.MATCH_DIRECT_BOOT_AWARE |
2555                    PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2556        } catch (RemoteException e) {
2557            // shouldn't happen.
2558        }
2559        if (ai == null) {
2560            throw new IllegalArgumentException("Unknown admin: " + adminName);
2561        }
2562
2563        if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2564            final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2565                    + permission.BIND_DEVICE_ADMIN;
2566            Slog.w(LOG_TAG, message);
2567            if (throwForMissiongPermission &&
2568                    ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2569                throw new IllegalArgumentException(message);
2570            }
2571        }
2572
2573        try {
2574            return new DeviceAdminInfo(mContext, ai);
2575        } catch (XmlPullParserException | IOException e) {
2576            Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2577                    e);
2578            return null;
2579        }
2580    }
2581
2582    private JournaledFile makeJournaledFile(int userHandle) {
2583        final String base = userHandle == UserHandle.USER_SYSTEM
2584                ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2585                : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2586                        DEVICE_POLICIES_XML).getAbsolutePath();
2587        if (VERBOSE_LOG) {
2588            Log.v(LOG_TAG, "Opening " + base);
2589        }
2590        return new JournaledFile(new File(base), new File(base + ".tmp"));
2591    }
2592
2593    private void saveSettingsLocked(int userHandle) {
2594        DevicePolicyData policy = getUserData(userHandle);
2595        JournaledFile journal = makeJournaledFile(userHandle);
2596        FileOutputStream stream = null;
2597        try {
2598            stream = new FileOutputStream(journal.chooseForWrite(), false);
2599            XmlSerializer out = new FastXmlSerializer();
2600            out.setOutput(stream, StandardCharsets.UTF_8.name());
2601            out.startDocument(null, true);
2602
2603            out.startTag(null, "policies");
2604            if (policy.mRestrictionsProvider != null) {
2605                out.attribute(null, ATTR_PERMISSION_PROVIDER,
2606                        policy.mRestrictionsProvider.flattenToString());
2607            }
2608            if (policy.mUserSetupComplete) {
2609                out.attribute(null, ATTR_SETUP_COMPLETE,
2610                        Boolean.toString(true));
2611            }
2612            if (policy.mPaired) {
2613                out.attribute(null, ATTR_DEVICE_PAIRED,
2614                        Boolean.toString(true));
2615            }
2616            if (policy.mDeviceProvisioningConfigApplied) {
2617                out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2618                        Boolean.toString(true));
2619            }
2620            if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2621                out.attribute(null, ATTR_PROVISIONING_STATE,
2622                        Integer.toString(policy.mUserProvisioningState));
2623            }
2624            if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2625                out.attribute(null, ATTR_PERMISSION_POLICY,
2626                        Integer.toString(policy.mPermissionPolicy));
2627            }
2628
2629            // Serialize delegations.
2630            for (int i = 0; i < policy.mDelegationMap.size(); ++i) {
2631                final String delegatePackage = policy.mDelegationMap.keyAt(i);
2632                final List<String> scopes = policy.mDelegationMap.valueAt(i);
2633
2634                // Every "delegation" tag serializes the information of one delegate-scope pair.
2635                for (String scope : scopes) {
2636                    out.startTag(null, "delegation");
2637                    out.attribute(null, "delegatePackage", delegatePackage);
2638                    out.attribute(null, "scope", scope);
2639                    out.endTag(null, "delegation");
2640                }
2641            }
2642
2643            final int N = policy.mAdminList.size();
2644            for (int i=0; i<N; i++) {
2645                ActiveAdmin ap = policy.mAdminList.get(i);
2646                if (ap != null) {
2647                    out.startTag(null, "admin");
2648                    out.attribute(null, "name", ap.info.getComponent().flattenToString());
2649                    ap.writeToXml(out);
2650                    out.endTag(null, "admin");
2651                }
2652            }
2653
2654            if (policy.mPasswordOwner >= 0) {
2655                out.startTag(null, "password-owner");
2656                out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2657                out.endTag(null, "password-owner");
2658            }
2659
2660            if (policy.mFailedPasswordAttempts != 0) {
2661                out.startTag(null, "failed-password-attempts");
2662                out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2663                out.endTag(null, "failed-password-attempts");
2664            }
2665
2666            // For FDE devices only, we save this flag so we can report on password sufficiency
2667            // before the user enters their password for the first time after a reboot.  For
2668            // security reasons, we don't want to store the full set of active password metrics.
2669            if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2670                out.startTag(null, TAG_PASSWORD_VALIDITY);
2671                out.attribute(null, ATTR_VALUE,
2672                        Boolean.toString(policy.mPasswordValidAtLastCheckpoint));
2673                out.endTag(null, TAG_PASSWORD_VALIDITY);
2674            }
2675
2676            for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2677                out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2678                out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2679                out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2680            }
2681
2682            for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2683                String component = policy.mLockTaskPackages.get(i);
2684                out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2685                out.attribute(null, "name", component);
2686                out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2687            }
2688
2689            if (policy.mLockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
2690                out.startTag(null, TAG_LOCK_TASK_FEATURES);
2691                out.attribute(null, ATTR_VALUE, Integer.toString(policy.mLockTaskFeatures));
2692                out.endTag(null, TAG_LOCK_TASK_FEATURES);
2693            }
2694
2695            if (policy.mStatusBarDisabled) {
2696                out.startTag(null, TAG_STATUS_BAR);
2697                out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2698                out.endTag(null, TAG_STATUS_BAR);
2699            }
2700
2701            if (policy.doNotAskCredentialsOnBoot) {
2702                out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2703                out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2704            }
2705
2706            for (String id : policy.mAffiliationIds) {
2707                out.startTag(null, TAG_AFFILIATION_ID);
2708                out.attribute(null, ATTR_ID, id);
2709                out.endTag(null, TAG_AFFILIATION_ID);
2710            }
2711
2712            if (policy.mLastSecurityLogRetrievalTime >= 0) {
2713                out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2714                out.attribute(null, ATTR_VALUE,
2715                        Long.toString(policy.mLastSecurityLogRetrievalTime));
2716                out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2717            }
2718
2719            if (policy.mLastBugReportRequestTime >= 0) {
2720                out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2721                out.attribute(null, ATTR_VALUE,
2722                        Long.toString(policy.mLastBugReportRequestTime));
2723                out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2724            }
2725
2726            if (policy.mLastNetworkLogsRetrievalTime >= 0) {
2727                out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2728                out.attribute(null, ATTR_VALUE,
2729                        Long.toString(policy.mLastNetworkLogsRetrievalTime));
2730                out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2731            }
2732
2733            if (policy.mAdminBroadcastPending) {
2734                out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2735                out.attribute(null, ATTR_VALUE,
2736                        Boolean.toString(policy.mAdminBroadcastPending));
2737                out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2738            }
2739
2740            if (policy.mInitBundle != null) {
2741                out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2742                policy.mInitBundle.saveToXml(out);
2743                out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2744            }
2745
2746            if (policy.mPasswordTokenHandle != 0) {
2747                out.startTag(null, TAG_PASSWORD_TOKEN_HANDLE);
2748                out.attribute(null, ATTR_VALUE,
2749                        Long.toString(policy.mPasswordTokenHandle));
2750                out.endTag(null, TAG_PASSWORD_TOKEN_HANDLE);
2751            }
2752
2753            if (policy.mCurrentInputMethodSet) {
2754                out.startTag(null, TAG_CURRENT_INPUT_METHOD_SET);
2755                out.endTag(null, TAG_CURRENT_INPUT_METHOD_SET);
2756            }
2757
2758            for (final String cert : policy.mOwnerInstalledCaCerts) {
2759                out.startTag(null, TAG_OWNER_INSTALLED_CA_CERT);
2760                out.attribute(null, ATTR_ALIAS, cert);
2761                out.endTag(null, TAG_OWNER_INSTALLED_CA_CERT);
2762            }
2763
2764            out.endTag(null, "policies");
2765
2766            out.endDocument();
2767            stream.flush();
2768            FileUtils.sync(stream);
2769            stream.close();
2770            journal.commit();
2771            sendChangedNotification(userHandle);
2772        } catch (XmlPullParserException | IOException e) {
2773            Slog.w(LOG_TAG, "failed writing file", e);
2774            try {
2775                if (stream != null) {
2776                    stream.close();
2777                }
2778            } catch (IOException ex) {
2779                // Ignore
2780            }
2781            journal.rollback();
2782        }
2783    }
2784
2785    private void sendChangedNotification(int userHandle) {
2786        Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2787        intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2788        long ident = mInjector.binderClearCallingIdentity();
2789        try {
2790            mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2791        } finally {
2792            mInjector.binderRestoreCallingIdentity(ident);
2793        }
2794    }
2795
2796    private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2797        JournaledFile journal = makeJournaledFile(userHandle);
2798        FileInputStream stream = null;
2799        File file = journal.chooseForRead();
2800        boolean needsRewrite = false;
2801        try {
2802            stream = new FileInputStream(file);
2803            XmlPullParser parser = Xml.newPullParser();
2804            parser.setInput(stream, StandardCharsets.UTF_8.name());
2805
2806            int type;
2807            while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2808                    && type != XmlPullParser.START_TAG) {
2809            }
2810            String tag = parser.getName();
2811            if (!"policies".equals(tag)) {
2812                throw new XmlPullParserException(
2813                        "Settings do not start with policies tag: found " + tag);
2814            }
2815
2816            // Extract the permission provider component name if available
2817            String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2818            if (permissionProvider != null) {
2819                policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2820            }
2821            String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2822            if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2823                policy.mUserSetupComplete = true;
2824            }
2825            String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
2826            if (paired != null && Boolean.toString(true).equals(paired)) {
2827                policy.mPaired = true;
2828            }
2829            String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2830                    ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2831            if (deviceProvisioningConfigApplied != null
2832                    && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2833                policy.mDeviceProvisioningConfigApplied = true;
2834            }
2835            String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2836            if (!TextUtils.isEmpty(provisioningState)) {
2837                policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2838            }
2839            String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2840            if (!TextUtils.isEmpty(permissionPolicy)) {
2841                policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2842            }
2843            // Check for delegation compatibility with pre-O.
2844            // TODO(edmanp) remove in P.
2845            {
2846                final String certDelegate = parser.getAttributeValue(null,
2847                        ATTR_DELEGATED_CERT_INSTALLER);
2848                if (certDelegate != null) {
2849                    List<String> scopes = policy.mDelegationMap.get(certDelegate);
2850                    if (scopes == null) {
2851                        scopes = new ArrayList<>();
2852                        policy.mDelegationMap.put(certDelegate, scopes);
2853                    }
2854                    if (!scopes.contains(DELEGATION_CERT_INSTALL)) {
2855                        scopes.add(DELEGATION_CERT_INSTALL);
2856                        needsRewrite = true;
2857                    }
2858                }
2859                final String appRestrictionsDelegate = parser.getAttributeValue(null,
2860                        ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2861                if (appRestrictionsDelegate != null) {
2862                    List<String> scopes = policy.mDelegationMap.get(appRestrictionsDelegate);
2863                    if (scopes == null) {
2864                        scopes = new ArrayList<>();
2865                        policy.mDelegationMap.put(appRestrictionsDelegate, scopes);
2866                    }
2867                    if (!scopes.contains(DELEGATION_APP_RESTRICTIONS)) {
2868                        scopes.add(DELEGATION_APP_RESTRICTIONS);
2869                        needsRewrite = true;
2870                    }
2871                }
2872            }
2873
2874            type = parser.next();
2875            int outerDepth = parser.getDepth();
2876            policy.mLockTaskPackages.clear();
2877            policy.mAdminList.clear();
2878            policy.mAdminMap.clear();
2879            policy.mAffiliationIds.clear();
2880            policy.mOwnerInstalledCaCerts.clear();
2881            while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2882                   && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2883                if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2884                    continue;
2885                }
2886                tag = parser.getName();
2887                if ("admin".equals(tag)) {
2888                    String name = parser.getAttributeValue(null, "name");
2889                    try {
2890                        DeviceAdminInfo dai = findAdmin(
2891                                ComponentName.unflattenFromString(name), userHandle,
2892                                /* throwForMissionPermission= */ false);
2893                        if (VERBOSE_LOG
2894                                && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2895                                != userHandle)) {
2896                            Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2897                                    + dai.getActivityInfo().applicationInfo.uid + " for user "
2898                                    + userHandle);
2899                        }
2900                        if (dai != null) {
2901                            ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2902                            ap.readFromXml(parser);
2903                            policy.mAdminMap.put(ap.info.getComponent(), ap);
2904                        }
2905                    } catch (RuntimeException e) {
2906                        Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2907                    }
2908                } else if ("delegation".equals(tag)) {
2909                    // Parse delegation info.
2910                    final String delegatePackage = parser.getAttributeValue(null,
2911                            "delegatePackage");
2912                    final String scope = parser.getAttributeValue(null, "scope");
2913
2914                    // Get a reference to the scopes list for the delegatePackage.
2915                    List<String> scopes = policy.mDelegationMap.get(delegatePackage);
2916                    // Or make a new list if none was found.
2917                    if (scopes == null) {
2918                        scopes = new ArrayList<>();
2919                        policy.mDelegationMap.put(delegatePackage, scopes);
2920                    }
2921                    // Add the new scope to the list of delegatePackage if it's not already there.
2922                    if (!scopes.contains(scope)) {
2923                        scopes.add(scope);
2924                    }
2925                } else if ("failed-password-attempts".equals(tag)) {
2926                    policy.mFailedPasswordAttempts = Integer.parseInt(
2927                            parser.getAttributeValue(null, "value"));
2928                } else if ("password-owner".equals(tag)) {
2929                    policy.mPasswordOwner = Integer.parseInt(
2930                            parser.getAttributeValue(null, "value"));
2931                } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2932                    policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2933                } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2934                    policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2935                } else if (TAG_LOCK_TASK_FEATURES.equals(tag)) {
2936                    policy.mLockTaskFeatures = Integer.parseInt(
2937                            parser.getAttributeValue(null, ATTR_VALUE));
2938                } else if (TAG_STATUS_BAR.equals(tag)) {
2939                    policy.mStatusBarDisabled = Boolean.parseBoolean(
2940                            parser.getAttributeValue(null, ATTR_DISABLED));
2941                } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2942                    policy.doNotAskCredentialsOnBoot = true;
2943                } else if (TAG_AFFILIATION_ID.equals(tag)) {
2944                    policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID));
2945                } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) {
2946                    policy.mLastSecurityLogRetrievalTime = Long.parseLong(
2947                            parser.getAttributeValue(null, ATTR_VALUE));
2948                } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) {
2949                    policy.mLastBugReportRequestTime = Long.parseLong(
2950                            parser.getAttributeValue(null, ATTR_VALUE));
2951                } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) {
2952                    policy.mLastNetworkLogsRetrievalTime = Long.parseLong(
2953                            parser.getAttributeValue(null, ATTR_VALUE));
2954                } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2955                    String pending = parser.getAttributeValue(null, ATTR_VALUE);
2956                    policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2957                } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2958                    policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2959                } else if ("active-password".equals(tag)) {
2960                    // Remove password metrics from saved settings, as we no longer wish to store
2961                    // these on disk
2962                    needsRewrite = true;
2963                } else if (TAG_PASSWORD_VALIDITY.equals(tag)) {
2964                    if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2965                        // This flag is only used for FDE devices
2966                        policy.mPasswordValidAtLastCheckpoint = Boolean.parseBoolean(
2967                                parser.getAttributeValue(null, ATTR_VALUE));
2968                    }
2969                } else if (TAG_PASSWORD_TOKEN_HANDLE.equals(tag)) {
2970                    policy.mPasswordTokenHandle = Long.parseLong(
2971                            parser.getAttributeValue(null, ATTR_VALUE));
2972                } else if (TAG_CURRENT_INPUT_METHOD_SET.equals(tag)) {
2973                    policy.mCurrentInputMethodSet = true;
2974                } else if (TAG_OWNER_INSTALLED_CA_CERT.equals(tag)) {
2975                    policy.mOwnerInstalledCaCerts.add(parser.getAttributeValue(null, ATTR_ALIAS));
2976                } else {
2977                    Slog.w(LOG_TAG, "Unknown tag: " + tag);
2978                    XmlUtils.skipCurrentTag(parser);
2979                }
2980            }
2981        } catch (FileNotFoundException e) {
2982            // Don't be noisy, this is normal if we haven't defined any policies.
2983        } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2984                | IndexOutOfBoundsException e) {
2985            Slog.w(LOG_TAG, "failed parsing " + file, e);
2986        }
2987        try {
2988            if (stream != null) {
2989                stream.close();
2990            }
2991        } catch (IOException e) {
2992            // Ignore
2993        }
2994
2995        // Generate a list of admins from the admin map
2996        policy.mAdminList.addAll(policy.mAdminMap.values());
2997
2998        // Might need to upgrade the file by rewriting it
2999        if (needsRewrite) {
3000            saveSettingsLocked(userHandle);
3001        }
3002
3003        validatePasswordOwnerLocked(policy);
3004        updateMaximumTimeToLockLocked(userHandle);
3005        updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
3006        updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle);
3007        if (policy.mStatusBarDisabled) {
3008            setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
3009        }
3010    }
3011
3012    private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
3013        long ident = mInjector.binderClearCallingIdentity();
3014        try {
3015            mInjector.getIActivityManager()
3016                    .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
3017        } catch (RemoteException e) {
3018            // Not gonna happen.
3019        } finally {
3020            mInjector.binderRestoreCallingIdentity(ident);
3021        }
3022    }
3023
3024    private void updateLockTaskFeaturesLocked(int flags, int userId) {
3025        long ident = mInjector.binderClearCallingIdentity();
3026        try {
3027            mInjector.getIActivityManager()
3028                    .updateLockTaskFeatures(userId, flags);
3029        } catch (RemoteException e) {
3030            // Not gonna happen.
3031        } finally {
3032            mInjector.binderRestoreCallingIdentity(ident);
3033        }
3034    }
3035
3036    private void updateDeviceOwnerLocked() {
3037        long ident = mInjector.binderClearCallingIdentity();
3038        try {
3039            // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
3040            // user id and also protect all other DAs too.
3041            final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
3042            if (deviceOwnerComponent != null) {
3043                mInjector.getIActivityManager()
3044                        .updateDeviceOwner(deviceOwnerComponent.getPackageName());
3045            }
3046        } catch (RemoteException e) {
3047            // Not gonna happen.
3048        } finally {
3049            mInjector.binderRestoreCallingIdentity(ident);
3050        }
3051    }
3052
3053    static void validateQualityConstant(int quality) {
3054        switch (quality) {
3055            case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
3056            case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
3057            case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
3058            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
3059            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
3060            case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
3061            case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
3062            case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
3063            case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
3064                return;
3065        }
3066        throw new IllegalArgumentException("Invalid quality constant: 0x"
3067                + Integer.toHexString(quality));
3068    }
3069
3070    void validatePasswordOwnerLocked(DevicePolicyData policy) {
3071        if (policy.mPasswordOwner >= 0) {
3072            boolean haveOwner = false;
3073            for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
3074                if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
3075                    haveOwner = true;
3076                    break;
3077                }
3078            }
3079            if (!haveOwner) {
3080                Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
3081                        + " no longer active; disabling");
3082                policy.mPasswordOwner = -1;
3083            }
3084        }
3085    }
3086
3087    @VisibleForTesting
3088    @Override
3089    void systemReady(int phase) {
3090        if (!mHasFeature) {
3091            return;
3092        }
3093        switch (phase) {
3094            case SystemService.PHASE_LOCK_SETTINGS_READY:
3095                onLockSettingsReady();
3096                break;
3097            case SystemService.PHASE_BOOT_COMPLETED:
3098                ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
3099                break;
3100        }
3101    }
3102
3103    private void onLockSettingsReady() {
3104        getUserData(UserHandle.USER_SYSTEM);
3105        loadOwners();
3106        cleanUpOldUsers();
3107        maybeSetDefaultProfileOwnerUserRestrictions();
3108        handleStartUser(UserHandle.USER_SYSTEM);
3109
3110        // Register an observer for watching for user setup complete and settings changes.
3111        mSetupContentObserver.register();
3112        // Initialize the user setup state, to handle the upgrade case.
3113        updateUserSetupCompleteAndPaired();
3114
3115        List<String> packageList;
3116        synchronized (this) {
3117            packageList = getKeepUninstalledPackagesLocked();
3118        }
3119        if (packageList != null) {
3120            mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
3121        }
3122
3123        synchronized (this) {
3124            // push the force-ephemeral-users policy to the user manager.
3125            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
3126            if (deviceOwner != null) {
3127                mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
3128            }
3129        }
3130    }
3131
3132    private void ensureDeviceOwnerUserStarted() {
3133        final int userId;
3134        synchronized (this) {
3135            if (!mOwners.hasDeviceOwner()) {
3136                return;
3137            }
3138            userId = mOwners.getDeviceOwnerUserId();
3139        }
3140        if (VERBOSE_LOG) {
3141            Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
3142        }
3143        if (userId != UserHandle.USER_SYSTEM) {
3144            try {
3145                mInjector.getIActivityManager().startUserInBackground(userId);
3146
3147                // STOPSHIP Prevent the DO user from being killed.
3148
3149            } catch (RemoteException e) {
3150                Slog.w(LOG_TAG, "Exception starting user", e);
3151            }
3152        }
3153    }
3154
3155    @Override
3156    void handleStartUser(int userId) {
3157        updateScreenCaptureDisabledInWindowManager(userId,
3158                getScreenCaptureDisabled(null, userId));
3159        pushUserRestrictions(userId);
3160
3161        startOwnerService(userId, "start-user");
3162    }
3163
3164    @Override
3165    void handleUnlockUser(int userId) {
3166        startOwnerService(userId, "unlock-user");
3167    }
3168
3169    @Override
3170    void handleStopUser(int userId) {
3171        stopOwnerService(userId, "stop-user");
3172    }
3173
3174    private void startOwnerService(int userId, String actionForLog) {
3175        final ComponentName owner = getOwnerComponent(userId);
3176        if (owner != null) {
3177            mDeviceAdminServiceController.startServiceForOwner(
3178                    owner.getPackageName(), userId, actionForLog);
3179        }
3180    }
3181
3182    private void stopOwnerService(int userId, String actionForLog) {
3183        mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog);
3184    }
3185
3186    private void cleanUpOldUsers() {
3187        // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
3188        // before reboot
3189        Set<Integer> usersWithProfileOwners;
3190        Set<Integer> usersWithData;
3191        synchronized(this) {
3192            usersWithProfileOwners = mOwners.getProfileOwnerKeys();
3193            usersWithData = new ArraySet<>();
3194            for (int i = 0; i < mUserData.size(); i++) {
3195                usersWithData.add(mUserData.keyAt(i));
3196            }
3197        }
3198        List<UserInfo> allUsers = mUserManager.getUsers();
3199
3200        Set<Integer> deletedUsers = new ArraySet<>();
3201        deletedUsers.addAll(usersWithProfileOwners);
3202        deletedUsers.addAll(usersWithData);
3203        for (UserInfo userInfo : allUsers) {
3204            deletedUsers.remove(userInfo.id);
3205        }
3206        for (Integer userId : deletedUsers) {
3207            removeUserData(userId);
3208        }
3209    }
3210
3211    private void handlePasswordExpirationNotification(int userHandle) {
3212        final Bundle adminExtras = new Bundle();
3213        adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
3214
3215        synchronized (this) {
3216            final long now = System.currentTimeMillis();
3217
3218            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
3219                    userHandle, /* parent */ false);
3220            final int N = admins.size();
3221            for (int i = 0; i < N; i++) {
3222                ActiveAdmin admin = admins.get(i);
3223                if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
3224                        && admin.passwordExpirationTimeout > 0L
3225                        && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
3226                        && admin.passwordExpirationDate > 0L) {
3227                    sendAdminCommandLocked(admin,
3228                            DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null);
3229                }
3230            }
3231            setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
3232        }
3233    }
3234
3235    /**
3236     * Clean up internal state when the set of installed trusted CA certificates changes.
3237     *
3238     * @param userHandle user to check for. This must be a real user and not, for example,
3239     *        {@link UserHandle#ALL}.
3240     * @param installedCertificates the full set of certificate authorities currently installed for
3241     *        {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will
3242     *        correspond to some subset of this.
3243     */
3244    protected void onInstalledCertificatesChanged(final UserHandle userHandle,
3245            final @NonNull Collection<String> installedCertificates) {
3246        if (!mHasFeature) {
3247            return;
3248        }
3249        enforceManageUsers();
3250
3251        synchronized (this) {
3252            final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3253
3254            boolean changed = false;
3255            changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates);
3256            changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates);
3257            if (changed) {
3258                saveSettingsLocked(userHandle.getIdentifier());
3259            }
3260        }
3261    }
3262
3263    /**
3264     * Internal method used by {@link CertificateMonitor}.
3265     */
3266    protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) {
3267        if (!mHasFeature) {
3268            return Collections.<String> emptySet();
3269        }
3270        synchronized (this) {
3271            final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3272            return policy.mAcceptedCaCertificates;
3273        }
3274    }
3275
3276    /**
3277     * @param adminReceiver The admin to add
3278     * @param refreshing true = update an active admin, no error
3279     */
3280    @Override
3281    public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
3282        if (!mHasFeature) {
3283            return;
3284        }
3285        setActiveAdmin(adminReceiver, refreshing, userHandle, null);
3286    }
3287
3288    private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
3289            Bundle onEnableData) {
3290        mContext.enforceCallingOrSelfPermission(
3291                android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3292        enforceFullCrossUsersPermission(userHandle);
3293
3294        DevicePolicyData policy = getUserData(userHandle);
3295        DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
3296                /* throwForMissionPermission= */ true);
3297        if (info == null) {
3298            throw new IllegalArgumentException("Bad admin: " + adminReceiver);
3299        }
3300        if (!info.getActivityInfo().applicationInfo.isInternal()) {
3301            throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
3302                    + adminReceiver);
3303        }
3304        if (info.getActivityInfo().applicationInfo.isInstantApp()) {
3305            throw new IllegalArgumentException("Instant apps cannot be device admins: "
3306                    + adminReceiver);
3307        }
3308        synchronized (this) {
3309            long ident = mInjector.binderClearCallingIdentity();
3310            try {
3311                final ActiveAdmin existingAdmin
3312                        = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3313                if (!refreshing && existingAdmin != null) {
3314                    throw new IllegalArgumentException("Admin is already added");
3315                }
3316                if (policy.mRemovingAdmins.contains(adminReceiver)) {
3317                    throw new IllegalArgumentException(
3318                            "Trying to set an admin which is being removed");
3319                }
3320                ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
3321                newAdmin.testOnlyAdmin =
3322                        (existingAdmin != null) ? existingAdmin.testOnlyAdmin
3323                                : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
3324                policy.mAdminMap.put(adminReceiver, newAdmin);
3325                int replaceIndex = -1;
3326                final int N = policy.mAdminList.size();
3327                for (int i=0; i < N; i++) {
3328                    ActiveAdmin oldAdmin = policy.mAdminList.get(i);
3329                    if (oldAdmin.info.getComponent().equals(adminReceiver)) {
3330                        replaceIndex = i;
3331                        break;
3332                    }
3333                }
3334                if (replaceIndex == -1) {
3335                    policy.mAdminList.add(newAdmin);
3336                    enableIfNecessary(info.getPackageName(), userHandle);
3337                } else {
3338                    policy.mAdminList.set(replaceIndex, newAdmin);
3339                }
3340                saveSettingsLocked(userHandle);
3341                sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3342                        onEnableData, null);
3343            } finally {
3344                mInjector.binderRestoreCallingIdentity(ident);
3345            }
3346        }
3347    }
3348
3349    @Override
3350    public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
3351        if (!mHasFeature) {
3352            return false;
3353        }
3354        enforceFullCrossUsersPermission(userHandle);
3355        synchronized (this) {
3356            return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
3357        }
3358    }
3359
3360    @Override
3361    public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
3362        if (!mHasFeature) {
3363            return false;
3364        }
3365        enforceFullCrossUsersPermission(userHandle);
3366        synchronized (this) {
3367            DevicePolicyData policyData = getUserData(userHandle);
3368            return policyData.mRemovingAdmins.contains(adminReceiver);
3369        }
3370    }
3371
3372    @Override
3373    public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
3374        if (!mHasFeature) {
3375            return false;
3376        }
3377        enforceFullCrossUsersPermission(userHandle);
3378        synchronized (this) {
3379            ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3380            if (administrator == null) {
3381                throw new SecurityException("No active admin " + adminReceiver);
3382            }
3383            return administrator.info.usesPolicy(policyId);
3384        }
3385    }
3386
3387    @Override
3388    @SuppressWarnings("unchecked")
3389    public List<ComponentName> getActiveAdmins(int userHandle) {
3390        if (!mHasFeature) {
3391            return Collections.EMPTY_LIST;
3392        }
3393
3394        enforceFullCrossUsersPermission(userHandle);
3395        synchronized (this) {
3396            DevicePolicyData policy = getUserData(userHandle);
3397            final int N = policy.mAdminList.size();
3398            if (N <= 0) {
3399                return null;
3400            }
3401            ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3402            for (int i=0; i<N; i++) {
3403                res.add(policy.mAdminList.get(i).info.getComponent());
3404            }
3405            return res;
3406        }
3407    }
3408
3409    @Override
3410    public boolean packageHasActiveAdmins(String packageName, int userHandle) {
3411        if (!mHasFeature) {
3412            return false;
3413        }
3414        enforceFullCrossUsersPermission(userHandle);
3415        synchronized (this) {
3416            DevicePolicyData policy = getUserData(userHandle);
3417            final int N = policy.mAdminList.size();
3418            for (int i=0; i<N; i++) {
3419                if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
3420                    return true;
3421                }
3422            }
3423            return false;
3424        }
3425    }
3426
3427    public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
3428        if (!mHasFeature) {
3429            return;
3430        }
3431        Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
3432        enforceShell("forceRemoveActiveAdmin");
3433        long ident = mInjector.binderClearCallingIdentity();
3434        try {
3435            synchronized (this)  {
3436                if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
3437                    throw new SecurityException("Attempt to remove non-test admin "
3438                            + adminReceiver + " " + userHandle);
3439                }
3440
3441                // If admin is a device or profile owner tidy that up first.
3442                if (isDeviceOwner(adminReceiver, userHandle)) {
3443                    clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3444                }
3445                if (isProfileOwner(adminReceiver, userHandle)) {
3446                    final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3447                            userHandle, /* parent */ false);
3448                    clearProfileOwnerLocked(admin, userHandle);
3449                }
3450            }
3451            // Remove the admin skipping sending the broadcast.
3452            removeAdminArtifacts(adminReceiver, userHandle);
3453            Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3454        } finally {
3455            mInjector.binderRestoreCallingIdentity(ident);
3456        }
3457    }
3458
3459    private void clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle) {
3460        // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state
3461        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
3462            mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle);
3463        }
3464    }
3465
3466    /**
3467     * Return if a given package has testOnly="true", in which case we'll relax certain rules
3468     * for CTS.
3469     *
3470     * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
3471     * to check wehter an active admin is test-only or not.
3472     *
3473     * The system allows this flag to be changed when an app is updated, which is not good
3474     * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3475     * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3476     */
3477    private boolean isPackageTestOnly(String packageName, int userHandle) {
3478        final ApplicationInfo ai;
3479        try {
3480            ai = mIPackageManager.getApplicationInfo(packageName,
3481                    (PackageManager.MATCH_DIRECT_BOOT_AWARE
3482                            | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3483        } catch (RemoteException e) {
3484            throw new IllegalStateException(e);
3485        }
3486        if (ai == null) {
3487            throw new IllegalStateException("Couldn't find package: "
3488                    + packageName + " on user " + userHandle);
3489        }
3490        return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3491    }
3492
3493    /**
3494     * See {@link #isPackageTestOnly}.
3495     */
3496    private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3497        final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3498        return (admin != null) && admin.testOnlyAdmin;
3499    }
3500
3501    private void enforceShell(String method) {
3502        final int callingUid = Binder.getCallingUid();
3503        if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3504            throw new SecurityException("Non-shell user attempted to call " + method);
3505        }
3506    }
3507
3508    @Override
3509    public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3510        if (!mHasFeature) {
3511            return;
3512        }
3513        enforceFullCrossUsersPermission(userHandle);
3514        enforceUserUnlocked(userHandle);
3515        synchronized (this) {
3516            ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3517            if (admin == null) {
3518                return;
3519            }
3520            // Active device/profile owners must remain active admins.
3521            if (isDeviceOwner(adminReceiver, userHandle)
3522                    || isProfileOwner(adminReceiver, userHandle)) {
3523                Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3524                        adminReceiver);
3525                return;
3526            }
3527            if (admin.getUid() != mInjector.binderGetCallingUid()) {
3528                mContext.enforceCallingOrSelfPermission(
3529                        android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3530            }
3531            long ident = mInjector.binderClearCallingIdentity();
3532            try {
3533                removeActiveAdminLocked(adminReceiver, userHandle);
3534            } finally {
3535                mInjector.binderRestoreCallingIdentity(ident);
3536            }
3537        }
3538    }
3539
3540    @Override
3541    public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3542        ComponentName profileOwner = getProfileOwner(userHandle);
3543        // Profile challenge is supported on N or newer release.
3544        return profileOwner != null &&
3545                getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3546    }
3547
3548    @Override
3549    public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3550        if (!mHasFeature) {
3551            return;
3552        }
3553        Preconditions.checkNotNull(who, "ComponentName is null");
3554        validateQualityConstant(quality);
3555
3556        synchronized (this) {
3557            ActiveAdmin ap = getActiveAdminForCallerLocked(
3558                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3559            if (ap.minimumPasswordMetrics.quality != quality) {
3560                ap.minimumPasswordMetrics.quality = quality;
3561                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3562                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3563            }
3564        }
3565    }
3566
3567    /**
3568     * Updates flag in memory that tells us whether the user's password currently satisfies the
3569     * requirements set by all of the user's active admins.  This should be called before
3570     * {@link #saveSettingsLocked} whenever the password or the admin policies have changed.
3571     */
3572    @GuardedBy("DevicePolicyManagerService.this")
3573    private void updatePasswordValidityCheckpointLocked(int userHandle) {
3574        DevicePolicyData policy = getUserData(userHandle);
3575        policy.mPasswordValidAtLastCheckpoint = isActivePasswordSufficientForUserLocked(
3576                policy, policy.mUserHandle, false);
3577    }
3578
3579    @Override
3580    public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3581        if (!mHasFeature) {
3582            return PASSWORD_QUALITY_UNSPECIFIED;
3583        }
3584        enforceFullCrossUsersPermission(userHandle);
3585        synchronized (this) {
3586            int mode = PASSWORD_QUALITY_UNSPECIFIED;
3587
3588            if (who != null) {
3589                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3590                return admin != null ? admin.minimumPasswordMetrics.quality : mode;
3591            }
3592
3593            // Return the strictest policy across all participating admins.
3594            List<ActiveAdmin> admins =
3595                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3596            final int N = admins.size();
3597            for (int i = 0; i < N; i++) {
3598                ActiveAdmin admin = admins.get(i);
3599                if (mode < admin.minimumPasswordMetrics.quality) {
3600                    mode = admin.minimumPasswordMetrics.quality;
3601                }
3602            }
3603            return mode;
3604        }
3605    }
3606
3607    private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3608            int userHandle, boolean parent) {
3609        if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3610            // If this user has a separate challenge, only return its restrictions.
3611            return getUserDataUnchecked(userHandle).mAdminList;
3612        } else {
3613            // Return all admins for this user and the profiles that are visible from this
3614            // user that do not use a separate work challenge.
3615            ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3616            for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3617                DevicePolicyData policy = getUserData(userInfo.id);
3618                if (!userInfo.isManagedProfile()) {
3619                    admins.addAll(policy.mAdminList);
3620                } else {
3621                    // For managed profiles, we always include the policies set on the parent
3622                    // profile. Additionally, we include the ones set on the managed profile
3623                    // if no separate challenge is in place.
3624                    boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3625                    final int N = policy.mAdminList.size();
3626                    for (int i = 0; i < N; i++) {
3627                        ActiveAdmin admin = policy.mAdminList.get(i);
3628                        if (admin.hasParentActiveAdmin()) {
3629                            admins.add(admin.getParentActiveAdmin());
3630                        }
3631                        if (!hasSeparateChallenge) {
3632                            admins.add(admin);
3633                        }
3634                    }
3635                }
3636            }
3637            return admins;
3638        }
3639    }
3640
3641    private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3642        long ident = mInjector.binderClearCallingIdentity();
3643        try {
3644            return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3645        } finally {
3646            mInjector.binderRestoreCallingIdentity(ident);
3647        }
3648    }
3649
3650    @Override
3651    public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3652        if (!mHasFeature) {
3653            return;
3654        }
3655        Preconditions.checkNotNull(who, "ComponentName is null");
3656        synchronized (this) {
3657            ActiveAdmin ap = getActiveAdminForCallerLocked(
3658                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3659            if (ap.minimumPasswordMetrics.length != length) {
3660                ap.minimumPasswordMetrics.length = length;
3661                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3662                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3663            }
3664        }
3665    }
3666
3667    @Override
3668    public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3669        return getStrictestPasswordRequirement(who, userHandle, parent,
3670                admin -> admin.minimumPasswordMetrics.length, PASSWORD_QUALITY_UNSPECIFIED);
3671    }
3672
3673    @Override
3674    public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3675        if (!mHasFeature) {
3676            return;
3677        }
3678        Preconditions.checkNotNull(who, "ComponentName is null");
3679        synchronized (this) {
3680            ActiveAdmin ap = getActiveAdminForCallerLocked(
3681                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3682            if (ap.passwordHistoryLength != length) {
3683                ap.passwordHistoryLength = length;
3684                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3685                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3686            }
3687        }
3688    }
3689
3690    @Override
3691    public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3692        return getStrictestPasswordRequirement(who, userHandle, parent,
3693                admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED);
3694    }
3695
3696    @Override
3697    public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3698        if (!mHasFeature) {
3699            return;
3700        }
3701        Preconditions.checkNotNull(who, "ComponentName is null");
3702        Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3703        final int userHandle = mInjector.userHandleGetCallingUserId();
3704        synchronized (this) {
3705            ActiveAdmin ap = getActiveAdminForCallerLocked(
3706                    who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3707            // Calling this API automatically bumps the expiration date
3708            final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3709            ap.passwordExpirationDate = expiration;
3710            ap.passwordExpirationTimeout = timeout;
3711            if (timeout > 0L) {
3712                Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3713                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3714                        .format(new Date(expiration)));
3715            }
3716            saveSettingsLocked(userHandle);
3717
3718            // in case this is the first one, set the alarm on the appropriate user.
3719            setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3720        }
3721    }
3722
3723    /**
3724     * Return a single admin's expiration cycle time, or the min of all cycle times.
3725     * Returns 0 if not configured.
3726     */
3727    @Override
3728    public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3729        if (!mHasFeature) {
3730            return 0L;
3731        }
3732        enforceFullCrossUsersPermission(userHandle);
3733        synchronized (this) {
3734            long timeout = 0L;
3735
3736            if (who != null) {
3737                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3738                return admin != null ? admin.passwordExpirationTimeout : timeout;
3739            }
3740
3741            // Return the strictest policy across all participating admins.
3742            List<ActiveAdmin> admins =
3743                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3744            final int N = admins.size();
3745            for (int i = 0; i < N; i++) {
3746                ActiveAdmin admin = admins.get(i);
3747                if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3748                        && timeout > admin.passwordExpirationTimeout)) {
3749                    timeout = admin.passwordExpirationTimeout;
3750                }
3751            }
3752            return timeout;
3753        }
3754    }
3755
3756    @Override
3757    public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3758        final int userId = UserHandle.getCallingUserId();
3759        List<String> changedProviders = null;
3760
3761        synchronized (this) {
3762            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3763                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3764            if (activeAdmin.crossProfileWidgetProviders == null) {
3765                activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3766            }
3767            List<String> providers = activeAdmin.crossProfileWidgetProviders;
3768            if (!providers.contains(packageName)) {
3769                providers.add(packageName);
3770                changedProviders = new ArrayList<>(providers);
3771                saveSettingsLocked(userId);
3772            }
3773        }
3774
3775        if (changedProviders != null) {
3776            mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3777            return true;
3778        }
3779
3780        return false;
3781    }
3782
3783    @Override
3784    public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3785        final int userId = UserHandle.getCallingUserId();
3786        List<String> changedProviders = null;
3787
3788        synchronized (this) {
3789            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3790                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3791            if (activeAdmin.crossProfileWidgetProviders == null
3792                    || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3793                return false;
3794            }
3795            List<String> providers = activeAdmin.crossProfileWidgetProviders;
3796            if (providers.remove(packageName)) {
3797                changedProviders = new ArrayList<>(providers);
3798                saveSettingsLocked(userId);
3799            }
3800        }
3801
3802        if (changedProviders != null) {
3803            mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3804            return true;
3805        }
3806
3807        return false;
3808    }
3809
3810    @Override
3811    public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3812        synchronized (this) {
3813            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3814                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3815            if (activeAdmin.crossProfileWidgetProviders == null
3816                    || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3817                return null;
3818            }
3819            if (mInjector.binderIsCallingUidMyUid()) {
3820                return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3821            } else {
3822                return activeAdmin.crossProfileWidgetProviders;
3823            }
3824        }
3825    }
3826
3827    /**
3828     * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3829     * Returns 0 if not configured.
3830     */
3831    private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3832        long timeout = 0L;
3833
3834        if (who != null) {
3835            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3836            return admin != null ? admin.passwordExpirationDate : timeout;
3837        }
3838
3839        // Return the strictest policy across all participating admins.
3840        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3841        final int N = admins.size();
3842        for (int i = 0; i < N; i++) {
3843            ActiveAdmin admin = admins.get(i);
3844            if (timeout == 0L || (admin.passwordExpirationDate != 0
3845                    && timeout > admin.passwordExpirationDate)) {
3846                timeout = admin.passwordExpirationDate;
3847            }
3848        }
3849        return timeout;
3850    }
3851
3852    @Override
3853    public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3854        if (!mHasFeature) {
3855            return 0L;
3856        }
3857        enforceFullCrossUsersPermission(userHandle);
3858        synchronized (this) {
3859            return getPasswordExpirationLocked(who, userHandle, parent);
3860        }
3861    }
3862
3863    @Override
3864    public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3865        if (!mHasFeature) {
3866            return;
3867        }
3868        Preconditions.checkNotNull(who, "ComponentName is null");
3869        synchronized (this) {
3870            ActiveAdmin ap = getActiveAdminForCallerLocked(
3871                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3872            if (ap.minimumPasswordMetrics.upperCase != length) {
3873                ap.minimumPasswordMetrics.upperCase = length;
3874                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3875                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3876            }
3877        }
3878    }
3879
3880    @Override
3881    public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3882        return getStrictestPasswordRequirement(who, userHandle, parent,
3883                admin -> admin.minimumPasswordMetrics.upperCase, PASSWORD_QUALITY_COMPLEX);
3884    }
3885
3886    @Override
3887    public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3888        Preconditions.checkNotNull(who, "ComponentName is null");
3889        synchronized (this) {
3890            ActiveAdmin ap = getActiveAdminForCallerLocked(
3891                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3892            if (ap.minimumPasswordMetrics.lowerCase != length) {
3893                ap.minimumPasswordMetrics.lowerCase = length;
3894                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3895                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3896            }
3897        }
3898    }
3899
3900    @Override
3901    public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3902        return getStrictestPasswordRequirement(who, userHandle, parent,
3903                admin -> admin.minimumPasswordMetrics.lowerCase, PASSWORD_QUALITY_COMPLEX);
3904    }
3905
3906    @Override
3907    public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3908        if (!mHasFeature) {
3909            return;
3910        }
3911        Preconditions.checkNotNull(who, "ComponentName is null");
3912        synchronized (this) {
3913            ActiveAdmin ap = getActiveAdminForCallerLocked(
3914                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3915            if (ap.minimumPasswordMetrics.letters != length) {
3916                ap.minimumPasswordMetrics.letters = length;
3917                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3918                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3919            }
3920        }
3921    }
3922
3923    @Override
3924    public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3925        return getStrictestPasswordRequirement(who, userHandle, parent,
3926                admin -> admin.minimumPasswordMetrics.letters, PASSWORD_QUALITY_COMPLEX);
3927    }
3928
3929    @Override
3930    public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3931        if (!mHasFeature) {
3932            return;
3933        }
3934        Preconditions.checkNotNull(who, "ComponentName is null");
3935        synchronized (this) {
3936            ActiveAdmin ap = getActiveAdminForCallerLocked(
3937                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3938            if (ap.minimumPasswordMetrics.numeric != length) {
3939                ap.minimumPasswordMetrics.numeric = length;
3940                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3941                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3942            }
3943        }
3944    }
3945
3946    @Override
3947    public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3948        return getStrictestPasswordRequirement(who, userHandle, parent,
3949                admin -> admin.minimumPasswordMetrics.numeric, PASSWORD_QUALITY_COMPLEX);
3950   }
3951
3952    @Override
3953    public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3954        if (!mHasFeature) {
3955            return;
3956        }
3957        Preconditions.checkNotNull(who, "ComponentName is null");
3958        synchronized (this) {
3959            ActiveAdmin ap = getActiveAdminForCallerLocked(
3960                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3961            if (ap.minimumPasswordMetrics.symbols != length) {
3962                ap.minimumPasswordMetrics.symbols = length;
3963                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3964                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3965            }
3966        }
3967    }
3968
3969    @Override
3970    public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3971        return getStrictestPasswordRequirement(who, userHandle, parent,
3972                admin -> admin.minimumPasswordMetrics.symbols, PASSWORD_QUALITY_COMPLEX);
3973    }
3974
3975    @Override
3976    public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3977        if (!mHasFeature) {
3978            return;
3979        }
3980        Preconditions.checkNotNull(who, "ComponentName is null");
3981        synchronized (this) {
3982            ActiveAdmin ap = getActiveAdminForCallerLocked(
3983                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3984            if (ap.minimumPasswordMetrics.nonLetter != length) {
3985                ap.minimumPasswordMetrics.nonLetter = length;
3986                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3987                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3988            }
3989        }
3990    }
3991
3992    @Override
3993    public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3994        return getStrictestPasswordRequirement(who, userHandle, parent,
3995                admin -> admin.minimumPasswordMetrics.nonLetter, PASSWORD_QUALITY_COMPLEX);
3996    }
3997
3998    /**
3999     * Calculates strictest (maximum) value for a given password property enforced by admin[s].
4000     */
4001    private int getStrictestPasswordRequirement(ComponentName who, int userHandle,
4002            boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) {
4003        if (!mHasFeature) {
4004            return 0;
4005        }
4006        enforceFullCrossUsersPermission(userHandle);
4007        synchronized (this) {
4008            if (who != null) {
4009                final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4010                return admin != null ? getter.apply(admin) : 0;
4011            }
4012
4013            int maxValue = 0;
4014            final List<ActiveAdmin> admins =
4015                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4016            final int N = admins.size();
4017            for (int i = 0; i < N; i++) {
4018                final ActiveAdmin admin = admins.get(i);
4019                if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) {
4020                    continue;
4021                }
4022                final Integer adminValue = getter.apply(admin);
4023                if (adminValue > maxValue) {
4024                    maxValue = adminValue;
4025                }
4026            }
4027            return maxValue;
4028        }
4029    }
4030
4031    @Override
4032    public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
4033        if (!mHasFeature) {
4034            return true;
4035        }
4036        enforceFullCrossUsersPermission(userHandle);
4037        enforceUserUnlocked(userHandle, parent);
4038
4039        synchronized (this) {
4040            // This API can only be called by an active device admin,
4041            // so try to retrieve it to check that the caller is one.
4042            getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4043            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4044            return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
4045        }
4046    }
4047
4048    @Override
4049    public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
4050        if (!mHasFeature) {
4051            return true;
4052        }
4053        enforceFullCrossUsersPermission(userHandle);
4054        enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
4055
4056        synchronized (this) {
4057            final int targetUser = getProfileParentId(userHandle);
4058            enforceUserUnlocked(targetUser, false);
4059            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
4060            return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
4061        }
4062    }
4063
4064    private boolean isActivePasswordSufficientForUserLocked(
4065            DevicePolicyData policy, int userHandle, boolean parent) {
4066        final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
4067        if (requiredPasswordQuality == PASSWORD_QUALITY_UNSPECIFIED) {
4068            // A special case is when there is no required password quality, then we just return
4069            // true since any password would be sufficient. This is for the scenario when a work
4070            // profile is first created so there is no information about the current password but
4071            // it should be considered sufficient as there is no password requirement either.
4072            // This is useful since it short-circuits the password checkpoint for FDE device below.
4073            return true;
4074        }
4075
4076        if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
4077                && !policy.mPasswordStateHasBeenSetSinceBoot) {
4078            // Before user enters their password for the first time after a reboot, return the
4079            // value of this flag, which tells us whether the password was valid the last time
4080            // settings were saved.  If DPC changes password requirements on boot so that the
4081            // current password no longer meets the requirements, this value will be stale until
4082            // the next time the password is entered.
4083            return policy.mPasswordValidAtLastCheckpoint;
4084        }
4085
4086        if (policy.mActivePasswordMetrics.quality < requiredPasswordQuality) {
4087            return false;
4088        }
4089        if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
4090                && policy.mActivePasswordMetrics.length < getPasswordMinimumLength(
4091                        null, userHandle, parent)) {
4092            return false;
4093        }
4094        if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4095            return true;
4096        }
4097        return policy.mActivePasswordMetrics.upperCase >= getPasswordMinimumUpperCase(
4098                    null, userHandle, parent)
4099                && policy.mActivePasswordMetrics.lowerCase >= getPasswordMinimumLowerCase(
4100                        null, userHandle, parent)
4101                && policy.mActivePasswordMetrics.letters >= getPasswordMinimumLetters(
4102                        null, userHandle, parent)
4103                && policy.mActivePasswordMetrics.numeric >= getPasswordMinimumNumeric(
4104                        null, userHandle, parent)
4105                && policy.mActivePasswordMetrics.symbols >= getPasswordMinimumSymbols(
4106                        null, userHandle, parent)
4107                && policy.mActivePasswordMetrics.nonLetter >= getPasswordMinimumNonLetter(
4108                        null, userHandle, parent);
4109    }
4110
4111    @Override
4112    public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
4113        enforceFullCrossUsersPermission(userHandle);
4114        synchronized (this) {
4115            if (!isCallerWithSystemUid()) {
4116                // This API can only be called by an active device admin,
4117                // so try to retrieve it to check that the caller is one.
4118                getActiveAdminForCallerLocked(
4119                        null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4120            }
4121
4122            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4123
4124            return policy.mFailedPasswordAttempts;
4125        }
4126    }
4127
4128    @Override
4129    public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
4130        if (!mHasFeature) {
4131            return;
4132        }
4133        Preconditions.checkNotNull(who, "ComponentName is null");
4134        synchronized (this) {
4135            // This API can only be called by an active device admin,
4136            // so try to retrieve it to check that the caller is one.
4137            getActiveAdminForCallerLocked(
4138                    who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
4139            ActiveAdmin ap = getActiveAdminForCallerLocked(
4140                    who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4141            if (ap.maximumFailedPasswordsForWipe != num) {
4142                ap.maximumFailedPasswordsForWipe = num;
4143                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4144            }
4145        }
4146    }
4147
4148    @Override
4149    public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
4150        if (!mHasFeature) {
4151            return 0;
4152        }
4153        enforceFullCrossUsersPermission(userHandle);
4154        synchronized (this) {
4155            ActiveAdmin admin = (who != null)
4156                    ? getActiveAdminUncheckedLocked(who, userHandle, parent)
4157                    : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
4158            return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
4159        }
4160    }
4161
4162    @Override
4163    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
4164        if (!mHasFeature) {
4165            return UserHandle.USER_NULL;
4166        }
4167        enforceFullCrossUsersPermission(userHandle);
4168        synchronized (this) {
4169            ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4170                    userHandle, parent);
4171            return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
4172        }
4173    }
4174
4175    /**
4176     * Returns the admin with the strictest policy on maximum failed passwords for:
4177     * <ul>
4178     *   <li>this user if it has a separate profile challenge, or
4179     *   <li>this user and all profiles that don't have their own challenge otherwise.
4180     * </ul>
4181     * <p>If the policy for the primary and any other profile are equal, it returns the admin for
4182     * the primary profile.
4183     * Returns {@code null} if no participating admin has that policy set.
4184     */
4185    private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
4186            int userHandle, boolean parent) {
4187        int count = 0;
4188        ActiveAdmin strictestAdmin = null;
4189
4190        // Return the strictest policy across all participating admins.
4191        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4192        final int N = admins.size();
4193        for (int i = 0; i < N; i++) {
4194            ActiveAdmin admin = admins.get(i);
4195            if (admin.maximumFailedPasswordsForWipe ==
4196                    ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
4197                continue;  // No max number of failed passwords policy set for this profile.
4198            }
4199
4200            // We always favor the primary profile if several profiles have the same value set.
4201            int userId = admin.getUserHandle().getIdentifier();
4202            if (count == 0 ||
4203                    count > admin.maximumFailedPasswordsForWipe ||
4204                    (count == admin.maximumFailedPasswordsForWipe &&
4205                            getUserInfo(userId).isPrimary())) {
4206                count = admin.maximumFailedPasswordsForWipe;
4207                strictestAdmin = admin;
4208            }
4209        }
4210        return strictestAdmin;
4211    }
4212
4213    private UserInfo getUserInfo(@UserIdInt int userId) {
4214        final long token = mInjector.binderClearCallingIdentity();
4215        try {
4216            return mUserManager.getUserInfo(userId);
4217        } finally {
4218            mInjector.binderRestoreCallingIdentity(token);
4219        }
4220    }
4221
4222    @Override
4223    public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
4224        final int callingUid = mInjector.binderGetCallingUid();
4225        final int userHandle = mInjector.userHandleGetCallingUserId();
4226
4227        String password = passwordOrNull != null ? passwordOrNull : "";
4228
4229        // Password resetting to empty/null is not allowed for managed profiles.
4230        if (TextUtils.isEmpty(password)) {
4231            enforceNotManagedProfile(userHandle, "clear the active password");
4232        }
4233
4234        synchronized (this) {
4235            // If caller has PO (or DO) it can change the password, so see if that's the case first.
4236            ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
4237                    null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
4238            final boolean preN;
4239            if (admin != null) {
4240                final int targetSdk = getTargetSdk(admin.info.getPackageName(), userHandle);
4241                if (targetSdk >= Build.VERSION_CODES.O) {
4242                    throw new SecurityException("resetPassword() is deprecated for DPC targeting O"
4243                            + " or later");
4244                }
4245                preN = targetSdk <= android.os.Build.VERSION_CODES.M;
4246            } else {
4247                // Otherwise, make sure the caller has any active admin with the right policy.
4248                admin = getActiveAdminForCallerLocked(null,
4249                        DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
4250                preN = getTargetSdk(admin.info.getPackageName(),
4251                        userHandle) <= android.os.Build.VERSION_CODES.M;
4252
4253                // As of N, password resetting to empty/null is not allowed anymore.
4254                // TODO Should we allow DO/PO to set an empty password?
4255                if (TextUtils.isEmpty(password)) {
4256                    if (!preN) {
4257                        throw new SecurityException("Cannot call with null password");
4258                    } else {
4259                        Slog.e(LOG_TAG, "Cannot call with null password");
4260                        return false;
4261                    }
4262                }
4263                // As of N, password cannot be changed by the admin if it is already set.
4264                if (isLockScreenSecureUnchecked(userHandle)) {
4265                    if (!preN) {
4266                        throw new SecurityException("Admin cannot change current password");
4267                    } else {
4268                        Slog.e(LOG_TAG, "Admin cannot change current password");
4269                        return false;
4270                    }
4271                }
4272            }
4273            // Do not allow to reset password when current user has a managed profile
4274            if (!isManagedProfile(userHandle)) {
4275                for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4276                    if (userInfo.isManagedProfile()) {
4277                        if (!preN) {
4278                            throw new IllegalStateException(
4279                                    "Cannot reset password on user has managed profile");
4280                        } else {
4281                            Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
4282                            return false;
4283                        }
4284                    }
4285                }
4286            }
4287            // Do not allow to reset password when user is locked
4288            if (!mUserManager.isUserUnlocked(userHandle)) {
4289                if (!preN) {
4290                    throw new IllegalStateException("Cannot reset password when user is locked");
4291                } else {
4292                    Slog.e(LOG_TAG, "Cannot reset password when user is locked");
4293                    return false;
4294                }
4295            }
4296        }
4297
4298        return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle);
4299    }
4300
4301    private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token,
4302            int flags, int callingUid, int userHandle) {
4303        int quality;
4304        synchronized (this) {
4305            quality = getPasswordQuality(null, userHandle, /* parent */ false);
4306            if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
4307                quality = PASSWORD_QUALITY_UNSPECIFIED;
4308            }
4309            final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password);
4310            if (quality != PASSWORD_QUALITY_UNSPECIFIED) {
4311                final int realQuality = metrics.quality;
4312                if (realQuality < quality
4313                        && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4314                    Slog.w(LOG_TAG, "resetPassword: password quality 0x"
4315                            + Integer.toHexString(realQuality)
4316                            + " does not meet required quality 0x"
4317                            + Integer.toHexString(quality));
4318                    return false;
4319                }
4320                quality = Math.max(realQuality, quality);
4321            }
4322            int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
4323            if (password.length() < length) {
4324                Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
4325                        + " does not meet required length " + length);
4326                return false;
4327            }
4328            if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4329                int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4330                if(metrics.letters < neededLetters) {
4331                    Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters
4332                            + " does not meet required number of letters " + neededLetters);
4333                    return false;
4334                }
4335                int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4336                if (metrics.numeric < neededNumeric) {
4337                    Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric
4338                            + " does not meet required number of numerical digits "
4339                            + neededNumeric);
4340                    return false;
4341                }
4342                int neededLowerCase = getPasswordMinimumLowerCase(
4343                        null, userHandle, /* parent */ false);
4344                if (metrics.lowerCase < neededLowerCase) {
4345                    Slog.w(LOG_TAG, "resetPassword: number of lowercase letters "
4346                            + metrics.lowerCase
4347                            + " does not meet required number of lowercase letters "
4348                            + neededLowerCase);
4349                    return false;
4350                }
4351                int neededUpperCase = getPasswordMinimumUpperCase(
4352                        null, userHandle, /* parent */ false);
4353                if (metrics.upperCase < neededUpperCase) {
4354                    Slog.w(LOG_TAG, "resetPassword: number of uppercase letters "
4355                            + metrics.upperCase
4356                            + " does not meet required number of uppercase letters "
4357                            + neededUpperCase);
4358                    return false;
4359                }
4360                int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4361                if (metrics.symbols < neededSymbols) {
4362                    Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols
4363                            + " does not meet required number of special symbols " + neededSymbols);
4364                    return false;
4365                }
4366                int neededNonLetter = getPasswordMinimumNonLetter(
4367                        null, userHandle, /* parent */ false);
4368                if (metrics.nonLetter < neededNonLetter) {
4369                    Slog.w(LOG_TAG, "resetPassword: number of non-letter characters "
4370                            + metrics.nonLetter
4371                            + " does not meet required number of non-letter characters "
4372                            + neededNonLetter);
4373                    return false;
4374                }
4375            }
4376        }
4377
4378        DevicePolicyData policy = getUserData(userHandle);
4379        if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4380            Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4381            return false;
4382        }
4383
4384        boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4385        boolean doNotAskCredentialsOnBoot =
4386                (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4387        if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4388            setDoNotAskCredentialsOnBoot();
4389        }
4390
4391        // Don't do this with the lock held, because it is going to call
4392        // back in to the service.
4393        final long ident = mInjector.binderClearCallingIdentity();
4394        final boolean result;
4395        try {
4396            if (token == null) {
4397                if (!TextUtils.isEmpty(password)) {
4398                    mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4399                } else {
4400                    mLockPatternUtils.clearLock(null, userHandle);
4401                }
4402                result = true;
4403            } else {
4404                result = mLockPatternUtils.setLockCredentialWithToken(password,
4405                        TextUtils.isEmpty(password) ? LockPatternUtils.CREDENTIAL_TYPE_NONE
4406                                : LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
4407                                quality, tokenHandle, token, userHandle);
4408            }
4409            boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4410            if (requireEntry) {
4411                mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4412                        UserHandle.USER_ALL);
4413            }
4414            synchronized (this) {
4415                int newOwner = requireEntry ? callingUid : -1;
4416                if (policy.mPasswordOwner != newOwner) {
4417                    policy.mPasswordOwner = newOwner;
4418                    saveSettingsLocked(userHandle);
4419                }
4420            }
4421        } finally {
4422            mInjector.binderRestoreCallingIdentity(ident);
4423        }
4424        return result;
4425    }
4426
4427    private boolean isLockScreenSecureUnchecked(int userId) {
4428        long ident = mInjector.binderClearCallingIdentity();
4429        try {
4430            return mLockPatternUtils.isSecure(userId);
4431        } finally {
4432            mInjector.binderRestoreCallingIdentity(ident);
4433        }
4434    }
4435
4436    private void setDoNotAskCredentialsOnBoot() {
4437        synchronized (this) {
4438            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4439            if (!policyData.doNotAskCredentialsOnBoot) {
4440                policyData.doNotAskCredentialsOnBoot = true;
4441                saveSettingsLocked(UserHandle.USER_SYSTEM);
4442            }
4443        }
4444    }
4445
4446    @Override
4447    public boolean getDoNotAskCredentialsOnBoot() {
4448        mContext.enforceCallingOrSelfPermission(
4449                android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4450        synchronized (this) {
4451            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4452            return policyData.doNotAskCredentialsOnBoot;
4453        }
4454    }
4455
4456    @Override
4457    public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4458        if (!mHasFeature) {
4459            return;
4460        }
4461        Preconditions.checkNotNull(who, "ComponentName is null");
4462        final int userHandle = mInjector.userHandleGetCallingUserId();
4463        synchronized (this) {
4464            ActiveAdmin ap = getActiveAdminForCallerLocked(
4465                    who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4466            if (ap.maximumTimeToUnlock != timeMs) {
4467                ap.maximumTimeToUnlock = timeMs;
4468                saveSettingsLocked(userHandle);
4469                updateMaximumTimeToLockLocked(userHandle);
4470            }
4471        }
4472    }
4473
4474    void updateMaximumTimeToLockLocked(int userHandle) {
4475        // Calculate the min timeout for all profiles - including the ones with a separate
4476        // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4477        // challenge only and keep the screen on. However there is no easy way of doing that at the
4478        // moment so we set the screen off timeout regardless of whether it affects the parent user
4479        // or the profile challenge only.
4480        long timeMs = Long.MAX_VALUE;
4481        int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4482        for (int profileId : profileIds) {
4483            DevicePolicyData policy = getUserDataUnchecked(profileId);
4484            final int N = policy.mAdminList.size();
4485            for (int i = 0; i < N; i++) {
4486                ActiveAdmin admin = policy.mAdminList.get(i);
4487                if (admin.maximumTimeToUnlock > 0
4488                        && timeMs > admin.maximumTimeToUnlock) {
4489                    timeMs = admin.maximumTimeToUnlock;
4490                }
4491                // If userInfo.id is a managed profile, we also need to look at
4492                // the policies set on the parent.
4493                if (admin.hasParentActiveAdmin()) {
4494                    final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4495                    if (parentAdmin.maximumTimeToUnlock > 0
4496                            && timeMs > parentAdmin.maximumTimeToUnlock) {
4497                        timeMs = parentAdmin.maximumTimeToUnlock;
4498                    }
4499                }
4500            }
4501        }
4502
4503        // We only store the last maximum time to lock on the parent profile. So if calling from a
4504        // managed profile, retrieve the policy for the parent.
4505        DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4506        if (policy.mLastMaximumTimeToLock == timeMs) {
4507            return;
4508        }
4509        policy.mLastMaximumTimeToLock = timeMs;
4510
4511        final long ident = mInjector.binderClearCallingIdentity();
4512        try {
4513            if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4514                // Make sure KEEP_SCREEN_ON is disabled, since that
4515                // would allow bypassing of the maximum time to lock.
4516                mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4517            }
4518
4519            mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4520                    (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4521        } finally {
4522            mInjector.binderRestoreCallingIdentity(ident);
4523        }
4524    }
4525
4526    @Override
4527    public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4528        if (!mHasFeature) {
4529            return 0;
4530        }
4531        enforceFullCrossUsersPermission(userHandle);
4532        synchronized (this) {
4533            if (who != null) {
4534                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4535                return admin != null ? admin.maximumTimeToUnlock : 0;
4536            }
4537            // Return the strictest policy across all participating admins.
4538            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4539                    userHandle, parent);
4540            return getMaximumTimeToLockPolicyFromAdmins(admins);
4541        }
4542    }
4543
4544    @Override
4545    public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4546        if (!mHasFeature) {
4547            return 0;
4548        }
4549        enforceFullCrossUsersPermission(userHandle);
4550        synchronized (this) {
4551            // All admins for this user.
4552            ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4553            for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4554                DevicePolicyData policy = getUserData(userInfo.id);
4555                admins.addAll(policy.mAdminList);
4556                // If it is a managed profile, it may have parent active admins
4557                if (userInfo.isManagedProfile()) {
4558                    for (ActiveAdmin admin : policy.mAdminList) {
4559                        if (admin.hasParentActiveAdmin()) {
4560                            admins.add(admin.getParentActiveAdmin());
4561                        }
4562                    }
4563                }
4564            }
4565            return getMaximumTimeToLockPolicyFromAdmins(admins);
4566        }
4567    }
4568
4569    private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4570        long time = 0;
4571        final int N = admins.size();
4572        for (int i = 0; i < N; i++) {
4573            ActiveAdmin admin = admins.get(i);
4574            if (time == 0) {
4575                time = admin.maximumTimeToUnlock;
4576            } else if (admin.maximumTimeToUnlock != 0
4577                    && time > admin.maximumTimeToUnlock) {
4578                time = admin.maximumTimeToUnlock;
4579            }
4580        }
4581        return time;
4582    }
4583
4584    @Override
4585    public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
4586            boolean parent) {
4587        if (!mHasFeature) {
4588            return;
4589        }
4590        Preconditions.checkNotNull(who, "ComponentName is null");
4591        Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
4592        // timeoutMs with value 0 means that the admin doesn't participate
4593        // timeoutMs is clamped to the interval in case the internal constants change in the future
4594        final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
4595        if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
4596            timeoutMs = minimumStrongAuthTimeout;
4597        }
4598        if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
4599            timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4600        }
4601
4602        final int userHandle = mInjector.userHandleGetCallingUserId();
4603        synchronized (this) {
4604            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4605                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4606            if (ap.strongAuthUnlockTimeout != timeoutMs) {
4607                ap.strongAuthUnlockTimeout = timeoutMs;
4608                saveSettingsLocked(userHandle);
4609            }
4610        }
4611    }
4612
4613    /**
4614     * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
4615     * admins if who is null.
4616     * Returns 0 if not configured for the provided admin.
4617     */
4618    @Override
4619    public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
4620        if (!mHasFeature) {
4621            return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4622        }
4623        enforceFullCrossUsersPermission(userId);
4624        synchronized (this) {
4625            if (who != null) {
4626                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
4627                return admin != null ? admin.strongAuthUnlockTimeout : 0;
4628            }
4629
4630            // Return the strictest policy across all participating admins.
4631            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
4632
4633            long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4634            for (int i = 0; i < admins.size(); i++) {
4635                final long timeout = admins.get(i).strongAuthUnlockTimeout;
4636                if (timeout != 0) { // take only participating admins into account
4637                    strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
4638                }
4639            }
4640            return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
4641        }
4642    }
4643
4644    private long getMinimumStrongAuthTimeoutMs() {
4645        if (!mInjector.isBuildDebuggable()) {
4646            return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
4647        }
4648        // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
4649        // name cannot be longer than 31 characters
4650        return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
4651                MINIMUM_STRONG_AUTH_TIMEOUT_MS),
4652                MINIMUM_STRONG_AUTH_TIMEOUT_MS);
4653    }
4654
4655    @Override
4656    public void lockNow(int flags, boolean parent) {
4657        if (!mHasFeature) {
4658            return;
4659        }
4660
4661        final int callingUserId = mInjector.userHandleGetCallingUserId();
4662        synchronized (this) {
4663            // This API can only be called by an active device admin,
4664            // so try to retrieve it to check that the caller is one.
4665            final ActiveAdmin admin = getActiveAdminForCallerLocked(
4666                    null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4667
4668            final long ident = mInjector.binderClearCallingIdentity();
4669            try {
4670                // Evict key
4671                if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
4672                    enforceManagedProfile(
4673                            callingUserId, "set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
4674                    if (!isProfileOwner(admin.info.getComponent(), callingUserId)) {
4675                        throw new SecurityException("Only profile owner admins can set "
4676                                + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
4677                    }
4678                    if (parent) {
4679                        throw new IllegalArgumentException(
4680                                "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent");
4681                    }
4682                    if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
4683                        throw new UnsupportedOperationException(
4684                                "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices");
4685                    }
4686                    mUserManager.evictCredentialEncryptionKey(callingUserId);
4687                }
4688
4689                // Lock all users unless this is a managed profile with a separate challenge
4690                final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
4691                        ? UserHandle.USER_ALL : callingUserId);
4692                mLockPatternUtils.requireStrongAuth(
4693                        STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4694
4695                // Require authentication for the device or profile
4696                if (userToLock == UserHandle.USER_ALL) {
4697                    // Power off the display
4698                    mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4699                            PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4700                    mInjector.getIWindowManager().lockNow(null);
4701                } else {
4702                    mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4703                }
4704            } catch (RemoteException e) {
4705            } finally {
4706                mInjector.binderRestoreCallingIdentity(ident);
4707            }
4708        }
4709    }
4710
4711    @Override
4712    public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
4713        if (who == null) {
4714            if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) {
4715                mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4716            }
4717        } else {
4718            enforceProfileOrDeviceOwner(who);
4719        }
4720    }
4721
4722    private void enforceProfileOrDeviceOwner(ComponentName who) {
4723        synchronized (this) {
4724            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4725        }
4726    }
4727
4728    @Override
4729    public boolean approveCaCert(String alias, int userId, boolean approval) {
4730        enforceManageUsers();
4731        synchronized (this) {
4732            Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4733            boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4734            if (!changed) {
4735                return false;
4736            }
4737            saveSettingsLocked(userId);
4738        }
4739        mCertificateMonitor.onCertificateApprovalsChanged(userId);
4740        return true;
4741    }
4742
4743    @Override
4744    public boolean isCaCertApproved(String alias, int userId) {
4745        enforceManageUsers();
4746        synchronized (this) {
4747            return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4748        }
4749    }
4750
4751    private void removeCaApprovalsIfNeeded(int userId) {
4752        for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4753            boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4754            if (userInfo.isManagedProfile()){
4755                isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4756            }
4757            if (!isSecure) {
4758                synchronized (this) {
4759                    getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4760                    saveSettingsLocked(userInfo.id);
4761                }
4762                mCertificateMonitor.onCertificateApprovalsChanged(userId);
4763            }
4764        }
4765    }
4766
4767    @Override
4768    public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)
4769            throws RemoteException {
4770        if (!mHasFeature) {
4771            return false;
4772        }
4773        enforceCanManageCaCerts(admin, callerPackage);
4774
4775        final String alias;
4776
4777        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
4778        final long id = mInjector.binderClearCallingIdentity();
4779        try {
4780            alias = mCertificateMonitor.installCaCert(userHandle, certBuffer);
4781            if (alias == null) {
4782                Log.w(LOG_TAG, "Problem installing cert");
4783                return false;
4784            }
4785        } finally {
4786            mInjector.binderRestoreCallingIdentity(id);
4787        }
4788
4789        synchronized (this) {
4790            getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias);
4791            saveSettingsLocked(userHandle.getIdentifier());
4792        }
4793        return true;
4794    }
4795
4796    @Override
4797    public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
4798        if (!mHasFeature) {
4799            return;
4800        }
4801        enforceCanManageCaCerts(admin, callerPackage);
4802
4803        final int userId = mInjector.userHandleGetCallingUserId();
4804        final long id = mInjector.binderClearCallingIdentity();
4805        try {
4806            mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases);
4807        } finally {
4808            mInjector.binderRestoreCallingIdentity(id);
4809        }
4810
4811        synchronized (this) {
4812            if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) {
4813                saveSettingsLocked(userId);
4814            }
4815        }
4816    }
4817
4818    @Override
4819    public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
4820            byte[] cert, byte[] chain, String alias, boolean requestAccess,
4821            boolean isUserSelectable) {
4822        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
4823                DELEGATION_CERT_INSTALL);
4824
4825
4826        final int callingUid = mInjector.binderGetCallingUid();
4827        final long id = mInjector.binderClearCallingIdentity();
4828        try {
4829            final KeyChainConnection keyChainConnection =
4830                    KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4831            try {
4832                IKeyChainService keyChain = keyChainConnection.getService();
4833                if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4834                    return false;
4835                }
4836                if (requestAccess) {
4837                    keyChain.setGrant(callingUid, alias, true);
4838                }
4839                keyChain.setUserSelectable(alias, isUserSelectable);
4840                return true;
4841            } catch (RemoteException e) {
4842                Log.e(LOG_TAG, "Installing certificate", e);
4843            } finally {
4844                keyChainConnection.close();
4845            }
4846        } catch (InterruptedException e) {
4847            Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4848            Thread.currentThread().interrupt();
4849        } finally {
4850            mInjector.binderRestoreCallingIdentity(id);
4851        }
4852        return false;
4853    }
4854
4855    @Override
4856    public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
4857        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
4858                DELEGATION_CERT_INSTALL);
4859
4860        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4861        final long id = Binder.clearCallingIdentity();
4862        try {
4863            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4864            try {
4865                IKeyChainService keyChain = keyChainConnection.getService();
4866                return keyChain.removeKeyPair(alias);
4867            } catch (RemoteException e) {
4868                Log.e(LOG_TAG, "Removing keypair", e);
4869            } finally {
4870                keyChainConnection.close();
4871            }
4872        } catch (InterruptedException e) {
4873            Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4874            Thread.currentThread().interrupt();
4875        } finally {
4876            Binder.restoreCallingIdentity(id);
4877        }
4878        return false;
4879    }
4880
4881    @Override
4882    public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm,
4883            ParcelableKeyGenParameterSpec parcelableKeySpec) {
4884        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
4885                DELEGATION_CERT_INSTALL);
4886        final KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec();
4887        if (TextUtils.isEmpty(keySpec.getKeystoreAlias())) {
4888            throw new IllegalArgumentException("Empty alias provided.");
4889        }
4890        // As the caller will be granted access to the key, ensure no UID was specified, as
4891        // it will not have the desired effect.
4892        if (keySpec.getUid() != KeyStore.UID_SELF) {
4893            Log.e(LOG_TAG, "Only the caller can be granted access to the generated keypair.");
4894            return false;
4895        }
4896        final int callingUid = mInjector.binderGetCallingUid();
4897
4898        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
4899        final long id = mInjector.binderClearCallingIdentity();
4900        try {
4901            try (KeyChainConnection keyChainConnection =
4902                    KeyChain.bindAsUser(mContext, userHandle)) {
4903                IKeyChainService keyChain = keyChainConnection.getService();
4904                final boolean generationResult = keyChain.generateKeyPair(algorithm, parcelableKeySpec);
4905                if (!generationResult) {
4906                    Log.e(LOG_TAG, "KeyChain failed to generate a keypair.");
4907                    return false;
4908                }
4909
4910                // Set a grant for the caller here so that when the client calls
4911                // requestPrivateKey, it will be able to get the key from Keystore.
4912                // Note the use of the calling  UID, since the request for the private
4913                // key will come from the client's process, so the grant has to be for
4914                // that UID.
4915                keyChain.setGrant(callingUid, keySpec.getKeystoreAlias(), true);
4916                return true;
4917            }
4918        } catch (RemoteException e) {
4919            Log.e(LOG_TAG, "KeyChain error while generating a keypair", e);
4920        } catch (InterruptedException e) {
4921            Log.w(LOG_TAG, "Interrupted while generating keypair", e);
4922            Thread.currentThread().interrupt();
4923        } finally {
4924            mInjector.binderRestoreCallingIdentity(id);
4925        }
4926        return false;
4927    }
4928
4929    @Override
4930    public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4931            final IBinder response) {
4932        // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4933        if (!isCallerWithSystemUid()) {
4934            return;
4935        }
4936
4937        final UserHandle caller = mInjector.binderGetCallingUserHandle();
4938        // If there is a profile owner, redirect to that; otherwise query the device owner.
4939        ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4940        if (aliasChooser == null && caller.isSystem()) {
4941            ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4942            if (deviceOwnerAdmin != null) {
4943                aliasChooser = deviceOwnerAdmin.info.getComponent();
4944            }
4945        }
4946        if (aliasChooser == null) {
4947            sendPrivateKeyAliasResponse(null, response);
4948            return;
4949        }
4950
4951        Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4952        intent.setComponent(aliasChooser);
4953        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4954        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4955        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4956        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4957        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4958
4959        final long id = mInjector.binderClearCallingIdentity();
4960        try {
4961            mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4962                @Override
4963                public void onReceive(Context context, Intent intent) {
4964                    final String chosenAlias = getResultData();
4965                    sendPrivateKeyAliasResponse(chosenAlias, response);
4966                }
4967            }, null, Activity.RESULT_OK, null, null);
4968        } finally {
4969            mInjector.binderRestoreCallingIdentity(id);
4970        }
4971    }
4972
4973    private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4974        final IKeyChainAliasCallback keyChainAliasResponse =
4975                IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4976        // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback
4977        // is oneway, which means it won't block if the recipient lives in another process.
4978        try {
4979            keyChainAliasResponse.alias(alias);
4980        } catch (Exception e) {
4981            // Caller could throw RuntimeException or RemoteException back across processes. Catch
4982            // everything just to be sure.
4983            Log.e(LOG_TAG, "error while responding to callback", e);
4984        }
4985    }
4986
4987    /**
4988     * Determine whether DPMS should check if a delegate package is already installed before
4989     * granting it new delegations via {@link #setDelegatedScopes}.
4990     */
4991    private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage,
4992            int targetSdk, List<String> scopes) {
4993        // 1) Never skip is installed check from N.
4994        if (targetSdk >= Build.VERSION_CODES.N) {
4995            return true;
4996        }
4997        // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given.
4998        if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) {
4999            return false;
5000        }
5001        // 3) Skip if all previously granted scopes are being cleared.
5002        if (scopes.isEmpty()) {
5003            return false;
5004        }
5005        // Otherwise it should check that delegatePackage is installed.
5006        return true;
5007    }
5008
5009    /**
5010     * Set the scopes of a device owner or profile owner delegate.
5011     *
5012     * @param who the device owner or profile owner.
5013     * @param delegatePackage the name of the delegate package.
5014     * @param scopes the list of delegation scopes to be given to the delegate package.
5015     */
5016    @Override
5017    public void setDelegatedScopes(ComponentName who, String delegatePackage,
5018            List<String> scopes) throws SecurityException {
5019        Preconditions.checkNotNull(who, "ComponentName is null");
5020        Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
5021        Preconditions.checkCollectionElementsNotNull(scopes, "Scopes");
5022        // Remove possible duplicates.
5023        scopes = new ArrayList(new ArraySet(scopes));
5024        // Ensure given scopes are valid.
5025        if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
5026            throw new IllegalArgumentException("Unexpected delegation scopes");
5027        }
5028
5029        // Retrieve the user ID of the calling process.
5030        final int userId = mInjector.userHandleGetCallingUserId();
5031        synchronized (this) {
5032            // Ensure calling process is device/profile owner.
5033            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5034            // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
5035            if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage,
5036                        getTargetSdk(who.getPackageName(), userId), scopes)) {
5037                // Throw when the delegate package is not installed.
5038                if (!isPackageInstalledForUser(delegatePackage, userId)) {
5039                    throw new IllegalArgumentException("Package " + delegatePackage
5040                            + " is not installed on the current user");
5041                }
5042            }
5043
5044            // Set the new delegate in user policies.
5045            final DevicePolicyData policy = getUserData(userId);
5046            if (!scopes.isEmpty()) {
5047                policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
5048            } else {
5049                // Remove any delegation info if the given scopes list is empty.
5050                policy.mDelegationMap.remove(delegatePackage);
5051            }
5052
5053            // Notify delegate package of updates.
5054            final Intent intent = new Intent(
5055                    DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
5056            // Only call receivers registered with Context#registerReceiver (don’t wake delegate).
5057            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
5058            // Limit components this intent resolves to to the delegate package.
5059            intent.setPackage(delegatePackage);
5060            // Include the list of delegated scopes as an extra.
5061            intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES,
5062                    (ArrayList<String>) scopes);
5063            // Send the broadcast.
5064            mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
5065
5066            // Persist updates.
5067            saveSettingsLocked(userId);
5068        }
5069    }
5070
5071    /**
5072     * Get the delegation scopes given to a delegate package by a device owner or profile owner.
5073     *
5074     * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
5075     * passing in {@code null} as the {@code who} parameter and its own name as the
5076     * {@code delegatepackage}.
5077     *
5078     * @param who the device owner or profile owner, or {@code null} if the caller is
5079     *            {@code delegatePackage}.
5080     * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
5081     * @return a list of the delegation scopes currently given to {@code delegatePackage}.
5082     */
5083    @Override
5084    @NonNull
5085    public List<String> getDelegatedScopes(ComponentName who,
5086            String delegatePackage) throws SecurityException {
5087        Preconditions.checkNotNull(delegatePackage, "Delegate package is null");
5088
5089        // Retrieve the user ID of the calling process.
5090        final int callingUid = mInjector.binderGetCallingUid();
5091        final int userId = UserHandle.getUserId(callingUid);
5092        synchronized (this) {
5093            // Ensure calling process is device/profile owner.
5094            if (who != null) {
5095                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5096            // Or ensure calling process is delegatePackage itself.
5097            } else {
5098                int uid = 0;
5099                try {
5100                  uid = mInjector.getPackageManager()
5101                          .getPackageUidAsUser(delegatePackage, userId);
5102                } catch(NameNotFoundException e) {
5103                }
5104                if (uid != callingUid) {
5105                    throw new SecurityException("Caller with uid " + callingUid + " is not "
5106                            + delegatePackage);
5107                }
5108            }
5109            final DevicePolicyData policy = getUserData(userId);
5110            // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
5111            final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5112            return scopes == null ? Collections.EMPTY_LIST : scopes;
5113        }
5114    }
5115
5116    /**
5117     * Get a list of  packages that were given a specific delegation scopes by a device owner or
5118     * profile owner.
5119     *
5120     * @param who the device owner or profile owner.
5121     * @param scope the scope whose delegates are to be retrieved.
5122     * @return a list of the delegate packages currently given the {@code scope} delegation.
5123     */
5124    @NonNull
5125    public List<String> getDelegatePackages(ComponentName who, String scope)
5126            throws SecurityException {
5127        Preconditions.checkNotNull(who, "ComponentName is null");
5128        Preconditions.checkNotNull(scope, "Scope is null");
5129        if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5130            throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5131        }
5132
5133        // Retrieve the user ID of the calling process.
5134        final int userId = mInjector.userHandleGetCallingUserId();
5135        synchronized (this) {
5136            // Ensure calling process is device/profile owner.
5137            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5138            final DevicePolicyData policy = getUserData(userId);
5139
5140            // Create a list to hold the resulting delegate packages.
5141            final List<String> delegatePackagesWithScope = new ArrayList<>();
5142            // Add all delegations containing scope to the result list.
5143            for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5144                if (policy.mDelegationMap.valueAt(i).contains(scope)) {
5145                    delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
5146                }
5147            }
5148            return delegatePackagesWithScope;
5149        }
5150    }
5151
5152    /**
5153     * Check whether a caller application has been delegated a given scope via
5154     * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
5155     * device owner.
5156     * <p>
5157     * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
5158     * then comparing the calling UID with the UID of {@code callerPackage} as reported by
5159     * {@link PackageManager#getPackageUidAsUser}.
5160     *
5161     * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
5162     * @param scope the delegation scope to be checked.
5163     * @return {@code true} if the calling process is a delegate of {@code scope}.
5164     */
5165    private boolean isCallerDelegate(String callerPackage, String scope) {
5166        Preconditions.checkNotNull(callerPackage, "callerPackage is null");
5167        if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5168            throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5169        }
5170
5171        // Retrieve the UID and user ID of the calling process.
5172        final int callingUid = mInjector.binderGetCallingUid();
5173        final int userId = UserHandle.getUserId(callingUid);
5174        synchronized (this) {
5175            // Retrieve user policy data.
5176            final DevicePolicyData policy = getUserData(userId);
5177            // Retrieve the list of delegation scopes granted to callerPackage.
5178            final List<String> scopes = policy.mDelegationMap.get(callerPackage);
5179            // Check callingUid only if callerPackage has the required scope delegation.
5180            if (scopes != null && scopes.contains(scope)) {
5181                try {
5182                    // Retrieve the expected UID for callerPackage.
5183                    final int uid = mInjector.getPackageManager()
5184                            .getPackageUidAsUser(callerPackage, userId);
5185                    // Return true if the caller is actually callerPackage.
5186                    return uid == callingUid;
5187                } catch (NameNotFoundException e) {
5188                    // Ignore.
5189                }
5190            }
5191            return false;
5192        }
5193    }
5194
5195    /**
5196     * Throw a security exception if a ComponentName is given and it is not a device/profile owner
5197     * or if the calling process is not a delegate of the given scope.
5198     *
5199     * @param who the device owner of profile owner, or null if {@code callerPackage} is a
5200     *            {@code scope} delegate.
5201     * @param callerPackage the name of the calling package. Required if {@code who} is
5202     *            {@code null}.
5203     * @param reqPolicy the policy used in the API whose access permission is being checked.
5204     * @param scope the delegation scope corresponding to the API being checked.
5205     * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy};
5206     *            or when {@code who} is {@code null} and {@code callerPackage} is not a delegate
5207     *            of {@code scope}.
5208     */
5209    private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy,
5210            String scope) {
5211        // If a ComponentName is given ensure it is a device or profile owner according to policy.
5212        if (who != null) {
5213            synchronized (this) {
5214                getActiveAdminForCallerLocked(who, reqPolicy);
5215            }
5216        // If no ComponentName is given ensure calling process has scope delegation.
5217        } else if (!isCallerDelegate(callerPackage, scope)) {
5218            throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid()
5219                    + " is not a delegate of scope " + scope + ".");
5220        }
5221    }
5222
5223    /**
5224     * Helper function to preserve delegation behavior pre-O when using the deprecated functions
5225     * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
5226     */
5227    private void setDelegatedScopePreO(ComponentName who,
5228            String delegatePackage, String scope) {
5229        Preconditions.checkNotNull(who, "ComponentName is null");
5230
5231        final int userId = mInjector.userHandleGetCallingUserId();
5232        synchronized(this) {
5233            // Ensure calling process is device/profile owner.
5234            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5235            final DevicePolicyData policy = getUserData(userId);
5236
5237            if (delegatePackage != null) {
5238                // Set package as a delegate for scope if it is not already one.
5239                List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5240                if (scopes == null) {
5241                    scopes = new ArrayList<>();
5242                }
5243                if (!scopes.contains(scope)) {
5244                    scopes.add(scope);
5245                    setDelegatedScopes(who, delegatePackage, scopes);
5246                }
5247            }
5248
5249            // Clear any existing scope delegates.
5250            for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5251                final String currentPackage = policy.mDelegationMap.keyAt(i);
5252                final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
5253
5254                if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) {
5255                    final List<String> newScopes = new ArrayList(currentScopes);
5256                    newScopes.remove(scope);
5257                    setDelegatedScopes(who, currentPackage, newScopes);
5258                }
5259            }
5260        }
5261    }
5262
5263    @Override
5264    public void setCertInstallerPackage(ComponentName who, String installerPackage)
5265            throws SecurityException {
5266        setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
5267    }
5268
5269    @Override
5270    public String getCertInstallerPackage(ComponentName who) throws SecurityException {
5271        final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
5272        return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
5273    }
5274
5275    /**
5276     * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
5277     * not installed and therefore not available.
5278     *
5279     * @throws SecurityException if the caller is not a profile or device owner.
5280     * @throws UnsupportedOperationException if the package does not support being set as always-on.
5281     */
5282    @Override
5283    public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
5284            throws SecurityException {
5285        enforceProfileOrDeviceOwner(admin);
5286
5287        final int userId = mInjector.userHandleGetCallingUserId();
5288        final long token = mInjector.binderClearCallingIdentity();
5289        try {
5290            if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
5291                return false;
5292            }
5293            ConnectivityManager connectivityManager = (ConnectivityManager)
5294                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5295            if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
5296                throw new UnsupportedOperationException();
5297            }
5298        } finally {
5299            mInjector.binderRestoreCallingIdentity(token);
5300        }
5301        return true;
5302    }
5303
5304    @Override
5305    public String getAlwaysOnVpnPackage(ComponentName admin)
5306            throws SecurityException {
5307        enforceProfileOrDeviceOwner(admin);
5308
5309        final int userId = mInjector.userHandleGetCallingUserId();
5310        final long token = mInjector.binderClearCallingIdentity();
5311        try{
5312            ConnectivityManager connectivityManager = (ConnectivityManager)
5313                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5314            return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
5315        } finally {
5316            mInjector.binderRestoreCallingIdentity(token);
5317        }
5318    }
5319
5320    private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc) {
5321        wtfIfInLock();
5322
5323        if (wipeExtRequested) {
5324            StorageManager sm = (StorageManager) mContext.getSystemService(
5325                    Context.STORAGE_SERVICE);
5326            sm.wipeAdoptableDisks();
5327        }
5328        try {
5329            mInjector.recoverySystemRebootWipeUserData(
5330                    /*shutdown=*/ false, reason, /*force=*/ true, /*wipeEuicc=*/ wipeEuicc);
5331        } catch (IOException | SecurityException e) {
5332            Slog.w(LOG_TAG, "Failed requesting data wipe", e);
5333        }
5334    }
5335
5336    private void forceWipeUser(int userId, String wipeReasonForUser) {
5337        try {
5338            IActivityManager am = mInjector.getIActivityManager();
5339            if (am.getCurrentUser().id == userId) {
5340                am.switchUser(UserHandle.USER_SYSTEM);
5341            }
5342
5343            boolean userRemoved = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
5344            if (!userRemoved) {
5345                Slog.w(LOG_TAG, "Couldn't remove user " + userId);
5346            } else if (isManagedProfile(userId)) {
5347                sendWipeProfileNotification(wipeReasonForUser);
5348            }
5349        } catch (RemoteException re) {
5350            // Shouldn't happen
5351        }
5352    }
5353
5354    @Override
5355    public void wipeDataWithReason(int flags, String wipeReasonForUser) {
5356        if (!mHasFeature) {
5357            return;
5358        }
5359        Preconditions.checkStringNotEmpty(wipeReasonForUser, "wipeReasonForUser is null or empty");
5360        enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId());
5361
5362        final ActiveAdmin admin;
5363        synchronized (this) {
5364            admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA);
5365        }
5366        String internalReason = "DevicePolicyManager.wipeDataWithReason() from "
5367                + admin.info.getComponent().flattenToShortString();
5368        wipeDataNoLock(
5369                admin.info.getComponent(), flags, internalReason, wipeReasonForUser,
5370                admin.getUserHandle().getIdentifier());
5371    }
5372
5373    private void wipeDataNoLock(ComponentName admin, int flags, String internalReason,
5374                                String wipeReasonForUser, int userId) {
5375        wtfIfInLock();
5376
5377        long ident = mInjector.binderClearCallingIdentity();
5378        try {
5379            // First check whether the admin is allowed to wipe the device/user/profile.
5380            final String restriction;
5381            if (userId == UserHandle.USER_SYSTEM) {
5382                restriction = UserManager.DISALLOW_FACTORY_RESET;
5383            } else if (isManagedProfile(userId)) {
5384                restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
5385            } else {
5386                restriction = UserManager.DISALLOW_REMOVE_USER;
5387            }
5388            if (isAdminAffectedByRestriction(admin, restriction, userId)) {
5389                throw new SecurityException("Cannot wipe data. " + restriction
5390                        + " restriction is set for user " + userId);
5391            }
5392
5393            if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
5394                if (!isDeviceOwner(admin, userId)) {
5395                    throw new SecurityException(
5396                            "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
5397                }
5398                PersistentDataBlockManager manager = (PersistentDataBlockManager)
5399                        mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
5400                if (manager != null) {
5401                    manager.wipe();
5402                }
5403            }
5404
5405            // TODO If split user is enabled and the device owner is set in the primary user
5406            // (rather than system), we should probably trigger factory reset. Current code just
5407            // removes that user (but still clears FRP...)
5408            if (userId == UserHandle.USER_SYSTEM) {
5409                forceWipeDeviceNoLock(/*wipeExtRequested=*/ (
5410                        flags & WIPE_EXTERNAL_STORAGE) != 0,
5411                        internalReason,
5412                        /*wipeEuicc=*/ (flags & WIPE_EUICC) != 0);
5413            } else {
5414                forceWipeUser(userId, wipeReasonForUser);
5415            }
5416        } finally {
5417            mInjector.binderRestoreCallingIdentity(ident);
5418        }
5419    }
5420
5421    private void sendWipeProfileNotification(String wipeReasonForUser) {
5422        Notification notification =
5423                new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
5424                        .setSmallIcon(android.R.drawable.stat_sys_warning)
5425                        .setContentTitle(mContext.getString(R.string.work_profile_deleted))
5426                        .setContentText(wipeReasonForUser)
5427                        .setColor(mContext.getColor(R.color.system_notification_accent_color))
5428                        .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser))
5429                        .build();
5430        mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification);
5431    }
5432
5433    private void clearWipeProfileNotification() {
5434        mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED);
5435    }
5436
5437    @Override
5438    public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
5439        if (!mHasFeature) {
5440            return;
5441        }
5442        enforceFullCrossUsersPermission(userHandle);
5443        mContext.enforceCallingOrSelfPermission(
5444                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5445
5446        synchronized (this) {
5447            ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
5448            if (admin == null) {
5449                result.sendResult(null);
5450                return;
5451            }
5452            Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
5453            intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
5454            intent.setComponent(admin.info.getComponent());
5455            mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
5456                    null, new BroadcastReceiver() {
5457                @Override
5458                public void onReceive(Context context, Intent intent) {
5459                    result.sendResult(getResultExtras(false));
5460                }
5461            }, null, Activity.RESULT_OK, null, null);
5462        }
5463    }
5464
5465    /**
5466     * Notify DPMS regarding the metric of the current password. This happens when the user changes
5467     * the password, but also when the user just unlocks the keyguard. In comparison,
5468     * reportPasswordChanged() is only called when the user changes the password.
5469     */
5470    @Override
5471    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
5472        if (!mHasFeature) {
5473            return;
5474        }
5475        enforceFullCrossUsersPermission(userHandle);
5476        mContext.enforceCallingOrSelfPermission(
5477                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5478
5479        // If the managed profile doesn't have a separate password, set the metrics to default
5480        if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
5481            metrics = new PasswordMetrics();
5482        }
5483
5484        validateQualityConstant(metrics.quality);
5485        DevicePolicyData policy = getUserData(userHandle);
5486        synchronized (this) {
5487            policy.mActivePasswordMetrics = metrics;
5488            policy.mPasswordStateHasBeenSetSinceBoot = true;
5489        }
5490    }
5491
5492    @Override
5493    public void reportPasswordChanged(@UserIdInt int userId) {
5494        if (!mHasFeature) {
5495            return;
5496        }
5497        enforceFullCrossUsersPermission(userId);
5498
5499        // Managed Profile password can only be changed when it has a separate challenge.
5500        if (!isSeparateProfileChallengeEnabled(userId)) {
5501            enforceNotManagedProfile(userId, "set the active password");
5502        }
5503
5504        mContext.enforceCallingOrSelfPermission(
5505                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5506
5507        DevicePolicyData policy = getUserData(userId);
5508
5509        long ident = mInjector.binderClearCallingIdentity();
5510        try {
5511            synchronized (this) {
5512                policy.mFailedPasswordAttempts = 0;
5513                updatePasswordValidityCheckpointLocked(userId);
5514                saveSettingsLocked(userId);
5515                updatePasswordExpirationsLocked(userId);
5516                setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
5517
5518                // Send a broadcast to each profile using this password as its primary unlock.
5519                sendAdminCommandForLockscreenPoliciesLocked(
5520                        DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
5521                        DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
5522            }
5523            removeCaApprovalsIfNeeded(userId);
5524        } finally {
5525            mInjector.binderRestoreCallingIdentity(ident);
5526        }
5527    }
5528
5529    /**
5530     * Called any time the device password is updated. Resets all password expiration clocks.
5531     */
5532    private void updatePasswordExpirationsLocked(int userHandle) {
5533        ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
5534        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5535                userHandle, /* parent */ false);
5536        final int N = admins.size();
5537        for (int i = 0; i < N; i++) {
5538            ActiveAdmin admin = admins.get(i);
5539            if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
5540                affectedUserIds.add(admin.getUserHandle().getIdentifier());
5541                long timeout = admin.passwordExpirationTimeout;
5542                long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
5543                admin.passwordExpirationDate = expiration;
5544            }
5545        }
5546        for (int affectedUserId : affectedUserIds) {
5547            saveSettingsLocked(affectedUserId);
5548        }
5549    }
5550
5551    @Override
5552    public void reportFailedPasswordAttempt(int userHandle) {
5553        enforceFullCrossUsersPermission(userHandle);
5554        if (!isSeparateProfileChallengeEnabled(userHandle)) {
5555            enforceNotManagedProfile(userHandle,
5556                    "report failed password attempt if separate profile challenge is not in place");
5557        }
5558        mContext.enforceCallingOrSelfPermission(
5559                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5560
5561        boolean wipeData = false;
5562        ActiveAdmin strictestAdmin = null;
5563        final long ident = mInjector.binderClearCallingIdentity();
5564        try {
5565            synchronized (this) {
5566                DevicePolicyData policy = getUserData(userHandle);
5567                policy.mFailedPasswordAttempts++;
5568                saveSettingsLocked(userHandle);
5569                if (mHasFeature) {
5570                    strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
5571                            userHandle, /* parent */ false);
5572                    int max = strictestAdmin != null
5573                            ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
5574                    if (max > 0 && policy.mFailedPasswordAttempts >= max) {
5575                        wipeData = true;
5576                    }
5577
5578                    sendAdminCommandForLockscreenPoliciesLocked(
5579                            DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
5580                            DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5581                }
5582            }
5583        } finally {
5584            mInjector.binderRestoreCallingIdentity(ident);
5585        }
5586
5587        if (wipeData && strictestAdmin != null) {
5588            final int userId = strictestAdmin.getUserHandle().getIdentifier();
5589            Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
5590                    + strictestAdmin.info.getComponent().flattenToShortString()
5591                    + ". Calling wipeData for user " + userId);
5592
5593            // Attempt to wipe the device/user/profile associated with the admin, as if the
5594            // admin had called wipeData(). That way we can check whether the admin is actually
5595            // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
5596            // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
5597            // able to do so).
5598            // IMPORTANT: Call without holding the lock to prevent deadlock.
5599            try {
5600                String wipeReasonForUser = mContext.getString(
5601                        R.string.work_profile_deleted_reason_maximum_password_failure);
5602                wipeDataNoLock(strictestAdmin.info.getComponent(),
5603                        /*flags=*/ 0,
5604                        /*reason=*/ "reportFailedPasswordAttempt()",
5605                        wipeReasonForUser,
5606                        userId);
5607            } catch (SecurityException e) {
5608                Slog.w(LOG_TAG, "Failed to wipe user " + userId
5609                        + " after max failed password attempts reached.", e);
5610            }
5611        }
5612
5613        if (mInjector.securityLogIsLoggingEnabled()) {
5614            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
5615                    /*result*/ 0,
5616                    /*method strength*/ 1);
5617        }
5618    }
5619
5620    @Override
5621    public void reportSuccessfulPasswordAttempt(int userHandle) {
5622        enforceFullCrossUsersPermission(userHandle);
5623        mContext.enforceCallingOrSelfPermission(
5624                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5625
5626        synchronized (this) {
5627            DevicePolicyData policy = getUserData(userHandle);
5628            if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
5629                long ident = mInjector.binderClearCallingIdentity();
5630                try {
5631                    policy.mFailedPasswordAttempts = 0;
5632                    policy.mPasswordOwner = -1;
5633                    saveSettingsLocked(userHandle);
5634                    if (mHasFeature) {
5635                        sendAdminCommandForLockscreenPoliciesLocked(
5636                                DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
5637                                DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5638                    }
5639                } finally {
5640                    mInjector.binderRestoreCallingIdentity(ident);
5641                }
5642            }
5643        }
5644
5645        if (mInjector.securityLogIsLoggingEnabled()) {
5646            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5647                    /*method strength*/ 1);
5648        }
5649    }
5650
5651    @Override
5652    public void reportFailedFingerprintAttempt(int userHandle) {
5653        enforceFullCrossUsersPermission(userHandle);
5654        mContext.enforceCallingOrSelfPermission(
5655                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5656        if (mInjector.securityLogIsLoggingEnabled()) {
5657            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5658                    /*method strength*/ 0);
5659        }
5660    }
5661
5662    @Override
5663    public void reportSuccessfulFingerprintAttempt(int userHandle) {
5664        enforceFullCrossUsersPermission(userHandle);
5665        mContext.enforceCallingOrSelfPermission(
5666                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5667        if (mInjector.securityLogIsLoggingEnabled()) {
5668            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5669                    /*method strength*/ 0);
5670        }
5671    }
5672
5673    @Override
5674    public void reportKeyguardDismissed(int userHandle) {
5675        enforceFullCrossUsersPermission(userHandle);
5676        mContext.enforceCallingOrSelfPermission(
5677                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5678
5679        if (mInjector.securityLogIsLoggingEnabled()) {
5680            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
5681        }
5682    }
5683
5684    @Override
5685    public void reportKeyguardSecured(int userHandle) {
5686        enforceFullCrossUsersPermission(userHandle);
5687        mContext.enforceCallingOrSelfPermission(
5688                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5689
5690        if (mInjector.securityLogIsLoggingEnabled()) {
5691            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
5692        }
5693    }
5694
5695    @Override
5696    public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
5697            String exclusionList) {
5698        if (!mHasFeature) {
5699            return null;
5700        }
5701        synchronized(this) {
5702            Preconditions.checkNotNull(who, "ComponentName is null");
5703
5704            // Only check if system user has set global proxy. We don't allow other users to set it.
5705            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5706            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5707                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
5708
5709            // Scan through active admins and find if anyone has already
5710            // set the global proxy.
5711            Set<ComponentName> compSet = policy.mAdminMap.keySet();
5712            for (ComponentName component : compSet) {
5713                ActiveAdmin ap = policy.mAdminMap.get(component);
5714                if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
5715                    // Another admin already sets the global proxy
5716                    // Return it to the caller.
5717                    return component;
5718                }
5719            }
5720
5721            // If the user is not system, don't set the global proxy. Fail silently.
5722            if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
5723                Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
5724                        + UserHandle.getCallingUserId() + " is not permitted.");
5725                return null;
5726            }
5727            if (proxySpec == null) {
5728                admin.specifiesGlobalProxy = false;
5729                admin.globalProxySpec = null;
5730                admin.globalProxyExclusionList = null;
5731            } else {
5732
5733                admin.specifiesGlobalProxy = true;
5734                admin.globalProxySpec = proxySpec;
5735                admin.globalProxyExclusionList = exclusionList;
5736            }
5737
5738            // Reset the global proxy accordingly
5739            // Do this using system permissions, as apps cannot write to secure settings
5740            long origId = mInjector.binderClearCallingIdentity();
5741            try {
5742                resetGlobalProxyLocked(policy);
5743            } finally {
5744                mInjector.binderRestoreCallingIdentity(origId);
5745            }
5746            return null;
5747        }
5748    }
5749
5750    @Override
5751    public ComponentName getGlobalProxyAdmin(int userHandle) {
5752        if (!mHasFeature) {
5753            return null;
5754        }
5755        enforceFullCrossUsersPermission(userHandle);
5756        synchronized(this) {
5757            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5758            // Scan through active admins and find if anyone has already
5759            // set the global proxy.
5760            final int N = policy.mAdminList.size();
5761            for (int i = 0; i < N; i++) {
5762                ActiveAdmin ap = policy.mAdminList.get(i);
5763                if (ap.specifiesGlobalProxy) {
5764                    // Device admin sets the global proxy
5765                    // Return it to the caller.
5766                    return ap.info.getComponent();
5767                }
5768            }
5769        }
5770        // No device admin sets the global proxy.
5771        return null;
5772    }
5773
5774    @Override
5775    public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5776        synchronized (this) {
5777            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5778        }
5779        long token = mInjector.binderClearCallingIdentity();
5780        try {
5781            ConnectivityManager connectivityManager = (ConnectivityManager)
5782                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5783            connectivityManager.setGlobalProxy(proxyInfo);
5784        } finally {
5785            mInjector.binderRestoreCallingIdentity(token);
5786        }
5787    }
5788
5789    private void resetGlobalProxyLocked(DevicePolicyData policy) {
5790        final int N = policy.mAdminList.size();
5791        for (int i = 0; i < N; i++) {
5792            ActiveAdmin ap = policy.mAdminList.get(i);
5793            if (ap.specifiesGlobalProxy) {
5794                saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5795                return;
5796            }
5797        }
5798        // No device admins defining global proxies - reset global proxy settings to none
5799        saveGlobalProxyLocked(null, null);
5800    }
5801
5802    private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5803        if (exclusionList == null) {
5804            exclusionList = "";
5805        }
5806        if (proxySpec == null) {
5807            proxySpec = "";
5808        }
5809        // Remove white spaces
5810        proxySpec = proxySpec.trim();
5811        String data[] = proxySpec.split(":");
5812        int proxyPort = 8080;
5813        if (data.length > 1) {
5814            try {
5815                proxyPort = Integer.parseInt(data[1]);
5816            } catch (NumberFormatException e) {}
5817        }
5818        exclusionList = exclusionList.trim();
5819
5820        ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5821        if (!proxyProperties.isValid()) {
5822            Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5823            return;
5824        }
5825        mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5826        mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5827        mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5828                exclusionList);
5829    }
5830
5831    /**
5832     * Set the storage encryption request for a single admin.  Returns the new total request
5833     * status (for all admins).
5834     */
5835    @Override
5836    public int setStorageEncryption(ComponentName who, boolean encrypt) {
5837        if (!mHasFeature) {
5838            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5839        }
5840        Preconditions.checkNotNull(who, "ComponentName is null");
5841        final int userHandle = UserHandle.getCallingUserId();
5842        synchronized (this) {
5843            // Check for permissions
5844            // Only system user can set storage encryption
5845            if (userHandle != UserHandle.USER_SYSTEM) {
5846                Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5847                        + UserHandle.getCallingUserId() + " is not permitted.");
5848                return 0;
5849            }
5850
5851            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5852                    DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5853
5854            // Quick exit:  If the filesystem does not support encryption, we can exit early.
5855            if (!isEncryptionSupported()) {
5856                return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5857            }
5858
5859            // (1) Record the value for the admin so it's sticky
5860            if (ap.encryptionRequested != encrypt) {
5861                ap.encryptionRequested = encrypt;
5862                saveSettingsLocked(userHandle);
5863            }
5864
5865            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5866            // (2) Compute "max" for all admins
5867            boolean newRequested = false;
5868            final int N = policy.mAdminList.size();
5869            for (int i = 0; i < N; i++) {
5870                newRequested |= policy.mAdminList.get(i).encryptionRequested;
5871            }
5872
5873            // Notify OS of new request
5874            setEncryptionRequested(newRequested);
5875
5876            // Return the new global request status
5877            return newRequested
5878                    ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5879                    : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5880        }
5881    }
5882
5883    /**
5884     * Get the current storage encryption request status for a given admin, or aggregate of all
5885     * active admins.
5886     */
5887    @Override
5888    public boolean getStorageEncryption(ComponentName who, int userHandle) {
5889        if (!mHasFeature) {
5890            return false;
5891        }
5892        enforceFullCrossUsersPermission(userHandle);
5893        synchronized (this) {
5894            // Check for permissions if a particular caller is specified
5895            if (who != null) {
5896                // When checking for a single caller, status is based on caller's request
5897                ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5898                return ap != null ? ap.encryptionRequested : false;
5899            }
5900
5901            // If no particular caller is specified, return the aggregate set of requests.
5902            // This is short circuited by returning true on the first hit.
5903            DevicePolicyData policy = getUserData(userHandle);
5904            final int N = policy.mAdminList.size();
5905            for (int i = 0; i < N; i++) {
5906                if (policy.mAdminList.get(i).encryptionRequested) {
5907                    return true;
5908                }
5909            }
5910            return false;
5911        }
5912    }
5913
5914    /**
5915     * Get the current encryption status of the device.
5916     */
5917    @Override
5918    public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5919        if (!mHasFeature) {
5920            // Ok to return current status.
5921        }
5922        enforceFullCrossUsersPermission(userHandle);
5923
5924        // It's not critical here, but let's make sure the package name is correct, in case
5925        // we start using it for different purposes.
5926        ensureCallerPackage(callerPackage);
5927
5928        final ApplicationInfo ai;
5929        try {
5930            ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5931        } catch (RemoteException e) {
5932            throw new SecurityException(e);
5933        }
5934
5935        boolean legacyApp = false;
5936        if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5937            legacyApp = true;
5938        }
5939
5940        final int rawStatus = getEncryptionStatus();
5941        if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5942            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5943        }
5944        return rawStatus;
5945    }
5946
5947    /**
5948     * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
5949     */
5950    private boolean isEncryptionSupported() {
5951        // Note, this can be implemented as
5952        //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5953        // But is provided as a separate internal method if there's a faster way to do a
5954        // simple check for supported-or-not.
5955        return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5956    }
5957
5958    /**
5959     * Hook to low-levels:  Reporting the current status of encryption.
5960     * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5961     * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5962     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5963     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5964     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5965     */
5966    private int getEncryptionStatus() {
5967        if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5968            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5969        } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5970            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5971        } else if (mInjector.storageManagerIsEncrypted()) {
5972            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5973        } else if (mInjector.storageManagerIsEncryptable()) {
5974            return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5975        } else {
5976            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5977        }
5978    }
5979
5980    /**
5981     * Hook to low-levels:  If needed, record the new admin setting for encryption.
5982     */
5983    private void setEncryptionRequested(boolean encrypt) {
5984    }
5985
5986    /**
5987     * Set whether the screen capture is disabled for the user managed by the specified admin.
5988     */
5989    @Override
5990    public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5991        if (!mHasFeature) {
5992            return;
5993        }
5994        Preconditions.checkNotNull(who, "ComponentName is null");
5995        final int userHandle = UserHandle.getCallingUserId();
5996        synchronized (this) {
5997            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5998                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5999            if (ap.disableScreenCapture != disabled) {
6000                ap.disableScreenCapture = disabled;
6001                saveSettingsLocked(userHandle);
6002                updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
6003            }
6004        }
6005    }
6006
6007    /**
6008     * Returns whether or not screen capture is disabled for a given admin, or disabled for any
6009     * active admin (if given admin is null).
6010     */
6011    @Override
6012    public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
6013        if (!mHasFeature) {
6014            return false;
6015        }
6016        synchronized (this) {
6017            if (who != null) {
6018                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6019                return (admin != null) ? admin.disableScreenCapture : false;
6020            }
6021
6022            DevicePolicyData policy = getUserData(userHandle);
6023            final int N = policy.mAdminList.size();
6024            for (int i = 0; i < N; i++) {
6025                ActiveAdmin admin = policy.mAdminList.get(i);
6026                if (admin.disableScreenCapture) {
6027                    return true;
6028                }
6029            }
6030            return false;
6031        }
6032    }
6033
6034    private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
6035            final boolean disabled) {
6036        mHandler.post(new Runnable() {
6037            @Override
6038            public void run() {
6039                try {
6040                    mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
6041                } catch (RemoteException e) {
6042                    Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
6043                }
6044            }
6045        });
6046    }
6047
6048    /**
6049     * Set whether auto time is required by the specified admin (must be device or profile owner).
6050     */
6051    @Override
6052    public void setAutoTimeRequired(ComponentName who, boolean required) {
6053        if (!mHasFeature) {
6054            return;
6055        }
6056        Preconditions.checkNotNull(who, "ComponentName is null");
6057        final int userHandle = UserHandle.getCallingUserId();
6058        synchronized (this) {
6059            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6060                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6061            if (admin.requireAutoTime != required) {
6062                admin.requireAutoTime = required;
6063                saveSettingsLocked(userHandle);
6064            }
6065        }
6066
6067        // Turn AUTO_TIME on in settings if it is required
6068        if (required) {
6069            long ident = mInjector.binderClearCallingIdentity();
6070            try {
6071                mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
6072            } finally {
6073                mInjector.binderRestoreCallingIdentity(ident);
6074            }
6075        }
6076    }
6077
6078    /**
6079     * Returns whether or not auto time is required by the device owner or any profile owner.
6080     */
6081    @Override
6082    public boolean getAutoTimeRequired() {
6083        if (!mHasFeature) {
6084            return false;
6085        }
6086        synchronized (this) {
6087            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6088            if (deviceOwner != null && deviceOwner.requireAutoTime) {
6089                // If the device owner enforces auto time, we don't need to check the PO's
6090                return true;
6091            }
6092
6093            // Now check to see if any profile owner on any user enforces auto time
6094            for (Integer userId : mOwners.getProfileOwnerKeys()) {
6095                ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
6096                if (profileOwner != null && profileOwner.requireAutoTime) {
6097                    return true;
6098                }
6099            }
6100
6101            return false;
6102        }
6103    }
6104
6105    @Override
6106    public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
6107        if (!mHasFeature) {
6108            return;
6109        }
6110        Preconditions.checkNotNull(who, "ComponentName is null");
6111        // Allow setting this policy to true only if there is a split system user.
6112        if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
6113            throw new UnsupportedOperationException(
6114                    "Cannot force ephemeral users on systems without split system user.");
6115        }
6116        boolean removeAllUsers = false;
6117        synchronized (this) {
6118            final ActiveAdmin deviceOwner =
6119                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6120            if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
6121                deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
6122                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
6123                mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
6124                removeAllUsers = forceEphemeralUsers;
6125            }
6126        }
6127        if (removeAllUsers) {
6128            long identitity = mInjector.binderClearCallingIdentity();
6129            try {
6130                mUserManagerInternal.removeAllUsers();
6131            } finally {
6132                mInjector.binderRestoreCallingIdentity(identitity);
6133            }
6134        }
6135    }
6136
6137    @Override
6138    public boolean getForceEphemeralUsers(ComponentName who) {
6139        if (!mHasFeature) {
6140            return false;
6141        }
6142        Preconditions.checkNotNull(who, "ComponentName is null");
6143        synchronized (this) {
6144            final ActiveAdmin deviceOwner =
6145                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6146            return deviceOwner.forceEphemeralUsers;
6147        }
6148    }
6149
6150    private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) throws SecurityException {
6151        synchronized (this) {
6152            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6153            if (!areAllUsersAffiliatedWithDeviceLocked()) {
6154                throw new SecurityException("Not all users are affiliated.");
6155            }
6156        }
6157    }
6158
6159    @Override
6160    public boolean requestBugreport(ComponentName who) {
6161        if (!mHasFeature) {
6162            return false;
6163        }
6164        Preconditions.checkNotNull(who, "ComponentName is null");
6165
6166        // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
6167        // which could still contain data related to that user. Should we disallow that, e.g. until
6168        // next boot? Might not be needed given that this still requires user consent.
6169        ensureDeviceOwnerAndAllUsersAffiliated(who);
6170
6171        if (mRemoteBugreportServiceIsActive.get()
6172                || (getDeviceOwnerRemoteBugreportUri() != null)) {
6173            Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
6174            return false;
6175        }
6176
6177        final long currentTime = System.currentTimeMillis();
6178        synchronized (this) {
6179            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
6180            if (currentTime > policyData.mLastBugReportRequestTime) {
6181                policyData.mLastBugReportRequestTime = currentTime;
6182                saveSettingsLocked(UserHandle.USER_SYSTEM);
6183            }
6184        }
6185
6186        final long callingIdentity = mInjector.binderClearCallingIdentity();
6187        try {
6188            mInjector.getIActivityManager().requestBugReport(
6189                    ActivityManager.BUGREPORT_OPTION_REMOTE);
6190
6191            mRemoteBugreportServiceIsActive.set(true);
6192            mRemoteBugreportSharingAccepted.set(false);
6193            registerRemoteBugreportReceivers();
6194            mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
6195                    RemoteBugreportUtils.NOTIFICATION_ID,
6196                    RemoteBugreportUtils.buildNotification(mContext,
6197                            DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
6198            mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
6199                    RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
6200            return true;
6201        } catch (RemoteException re) {
6202            // should never happen
6203            Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
6204            return false;
6205        } finally {
6206            mInjector.binderRestoreCallingIdentity(callingIdentity);
6207        }
6208    }
6209
6210    synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
6211        Intent intent = new Intent(action);
6212        intent.setComponent(mOwners.getDeviceOwnerComponent());
6213        if (extras != null) {
6214            intent.putExtras(extras);
6215        }
6216        mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
6217    }
6218
6219    private synchronized String getDeviceOwnerRemoteBugreportUri() {
6220        return mOwners.getDeviceOwnerRemoteBugreportUri();
6221    }
6222
6223    private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
6224            String bugreportHash) {
6225        mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
6226    }
6227
6228    private void registerRemoteBugreportReceivers() {
6229        try {
6230            IntentFilter filterFinished = new IntentFilter(
6231                    DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
6232                    RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6233            mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
6234        } catch (IntentFilter.MalformedMimeTypeException e) {
6235            // should never happen, as setting a constant
6236            Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
6237        }
6238        IntentFilter filterConsent = new IntentFilter();
6239        filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
6240        filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
6241        mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
6242    }
6243
6244    private void onBugreportFinished(Intent intent) {
6245        mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6246        mRemoteBugreportServiceIsActive.set(false);
6247        Uri bugreportUri = intent.getData();
6248        String bugreportUriString = null;
6249        if (bugreportUri != null) {
6250            bugreportUriString = bugreportUri.toString();
6251        }
6252        String bugreportHash = intent.getStringExtra(
6253                DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
6254        if (mRemoteBugreportSharingAccepted.get()) {
6255            shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6256            mInjector.getNotificationManager().cancel(LOG_TAG,
6257                    RemoteBugreportUtils.NOTIFICATION_ID);
6258        } else {
6259            setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
6260            mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6261                    RemoteBugreportUtils.buildNotification(mContext,
6262                            DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
6263                            UserHandle.ALL);
6264        }
6265        mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6266    }
6267
6268    private void onBugreportFailed() {
6269        mRemoteBugreportServiceIsActive.set(false);
6270        mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6271                RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6272        mRemoteBugreportSharingAccepted.set(false);
6273        setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6274        mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
6275        Bundle extras = new Bundle();
6276        extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6277                DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
6278        sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6279        mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
6280        mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6281    }
6282
6283    private void onBugreportSharingAccepted() {
6284        mRemoteBugreportSharingAccepted.set(true);
6285        String bugreportUriString = null;
6286        String bugreportHash = null;
6287        synchronized (this) {
6288            bugreportUriString = getDeviceOwnerRemoteBugreportUri();
6289            bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
6290        }
6291        if (bugreportUriString != null) {
6292            shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6293        } else if (mRemoteBugreportServiceIsActive.get()) {
6294            mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6295                    RemoteBugreportUtils.buildNotification(mContext,
6296                            DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
6297                            UserHandle.ALL);
6298        }
6299    }
6300
6301    private void onBugreportSharingDeclined() {
6302        if (mRemoteBugreportServiceIsActive.get()) {
6303            mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6304                    RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6305            mRemoteBugreportServiceIsActive.set(false);
6306            mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6307            mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6308        }
6309        mRemoteBugreportSharingAccepted.set(false);
6310        setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6311        sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
6312    }
6313
6314    private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
6315            String bugreportHash) {
6316        ParcelFileDescriptor pfd = null;
6317        try {
6318            if (bugreportUriString == null) {
6319                throw new FileNotFoundException();
6320            }
6321            Uri bugreportUri = Uri.parse(bugreportUriString);
6322            pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
6323
6324            synchronized (this) {
6325                Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
6326                intent.setComponent(mOwners.getDeviceOwnerComponent());
6327                intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6328                intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
6329                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
6330
6331                LocalServices.getService(ActivityManagerInternal.class)
6332                        .grantUriPermissionFromIntent(Process.SHELL_UID,
6333                                mOwners.getDeviceOwnerComponent().getPackageName(),
6334                                intent, mOwners.getDeviceOwnerUserId());
6335                mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
6336            }
6337        } catch (FileNotFoundException e) {
6338            Bundle extras = new Bundle();
6339            extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6340                    DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
6341            sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6342        } finally {
6343            try {
6344                if (pfd != null) {
6345                    pfd.close();
6346                }
6347            } catch (IOException ex) {
6348                // Ignore
6349            }
6350            mRemoteBugreportSharingAccepted.set(false);
6351            setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6352        }
6353    }
6354
6355    /**
6356     * Disables all device cameras according to the specified admin.
6357     */
6358    @Override
6359    public void setCameraDisabled(ComponentName who, boolean disabled) {
6360        if (!mHasFeature) {
6361            return;
6362        }
6363        Preconditions.checkNotNull(who, "ComponentName is null");
6364        final int userHandle = mInjector.userHandleGetCallingUserId();
6365        synchronized (this) {
6366            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6367                    DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
6368            if (ap.disableCamera != disabled) {
6369                ap.disableCamera = disabled;
6370                saveSettingsLocked(userHandle);
6371            }
6372        }
6373        // Tell the user manager that the restrictions have changed.
6374        pushUserRestrictions(userHandle);
6375    }
6376
6377    /**
6378     * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
6379     * active admins.
6380     */
6381    @Override
6382    public boolean getCameraDisabled(ComponentName who, int userHandle) {
6383        return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
6384    }
6385
6386    private boolean getCameraDisabled(ComponentName who, int userHandle,
6387            boolean mergeDeviceOwnerRestriction) {
6388        if (!mHasFeature) {
6389            return false;
6390        }
6391        synchronized (this) {
6392            if (who != null) {
6393                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6394                return (admin != null) ? admin.disableCamera : false;
6395            }
6396            // First, see if DO has set it.  If so, it's device-wide.
6397            if (mergeDeviceOwnerRestriction) {
6398                final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6399                if (deviceOwner != null && deviceOwner.disableCamera) {
6400                    return true;
6401                }
6402            }
6403
6404            // Then check each device admin on the user.
6405            DevicePolicyData policy = getUserData(userHandle);
6406            // Determine whether or not the device camera is disabled for any active admins.
6407            final int N = policy.mAdminList.size();
6408            for (int i = 0; i < N; i++) {
6409                ActiveAdmin admin = policy.mAdminList.get(i);
6410                if (admin.disableCamera) {
6411                    return true;
6412                }
6413            }
6414            return false;
6415        }
6416    }
6417
6418    @Override
6419    public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
6420        if (!mHasFeature) {
6421            return;
6422        }
6423        Preconditions.checkNotNull(who, "ComponentName is null");
6424        final int userHandle = mInjector.userHandleGetCallingUserId();
6425        if (isManagedProfile(userHandle)) {
6426            if (parent) {
6427                which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
6428            } else {
6429                which = which & PROFILE_KEYGUARD_FEATURES;
6430            }
6431        }
6432        synchronized (this) {
6433            ActiveAdmin ap = getActiveAdminForCallerLocked(
6434                    who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6435            if (ap.disabledKeyguardFeatures != which) {
6436                ap.disabledKeyguardFeatures = which;
6437                saveSettingsLocked(userHandle);
6438            }
6439        }
6440    }
6441
6442    /**
6443     * Gets the disabled state for features in keyguard for the given admin,
6444     * or the aggregate of all active admins if who is null.
6445     */
6446    @Override
6447    public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
6448        if (!mHasFeature) {
6449            return 0;
6450        }
6451        enforceFullCrossUsersPermission(userHandle);
6452        final long ident = mInjector.binderClearCallingIdentity();
6453        try {
6454            synchronized (this) {
6455                if (who != null) {
6456                    ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
6457                    return (admin != null) ? admin.disabledKeyguardFeatures : 0;
6458                }
6459
6460                final List<ActiveAdmin> admins;
6461                if (!parent && isManagedProfile(userHandle)) {
6462                    // If we are being asked about a managed profile, just return keyguard features
6463                    // disabled by admins in the profile.
6464                    admins = getUserDataUnchecked(userHandle).mAdminList;
6465                } else {
6466                    // Otherwise return those set by admins in the user and its profiles.
6467                    admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6468                }
6469
6470                int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
6471                final int N = admins.size();
6472                for (int i = 0; i < N; i++) {
6473                    ActiveAdmin admin = admins.get(i);
6474                    int userId = admin.getUserHandle().getIdentifier();
6475                    boolean isRequestedUser = !parent && (userId == userHandle);
6476                    if (isRequestedUser || !isManagedProfile(userId)) {
6477                        // If we are being asked explicitly about this user
6478                        // return all disabled features even if its a managed profile.
6479                        which |= admin.disabledKeyguardFeatures;
6480                    } else {
6481                        // Otherwise a managed profile is only allowed to disable
6482                        // some features on the parent user.
6483                        which |= (admin.disabledKeyguardFeatures
6484                                & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
6485                    }
6486                }
6487                return which;
6488            }
6489        } finally {
6490            mInjector.binderRestoreCallingIdentity(ident);
6491        }
6492    }
6493
6494    @Override
6495    public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
6496            List<String> packageList) {
6497        if (!mHasFeature) {
6498            return;
6499        }
6500        Preconditions.checkNotNull(packageList, "packageList is null");
6501        final int userHandle = UserHandle.getCallingUserId();
6502        synchronized (this) {
6503            // Ensure the caller is a DO or a keep uninstalled packages delegate.
6504            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6505                    DELEGATION_KEEP_UNINSTALLED_PACKAGES);
6506            // Get the device owner
6507            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6508            // Set list of packages to be kept even if uninstalled.
6509            deviceOwner.keepUninstalledPackages = packageList;
6510            // Save settings.
6511            saveSettingsLocked(userHandle);
6512            // Notify package manager.
6513            mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
6514        }
6515    }
6516
6517    @Override
6518    public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
6519        if (!mHasFeature) {
6520            return null;
6521        }
6522        // TODO In split system user mode, allow apps on user 0 to query the list
6523        synchronized (this) {
6524            // Ensure the caller is a DO or a keep uninstalled packages delegate.
6525            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6526                    DELEGATION_KEEP_UNINSTALLED_PACKAGES);
6527            return getKeepUninstalledPackagesLocked();
6528        }
6529    }
6530
6531    private List<String> getKeepUninstalledPackagesLocked() {
6532        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6533        return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
6534    }
6535
6536    @Override
6537    public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
6538        if (!mHasFeature) {
6539            return false;
6540        }
6541        if (admin == null
6542                || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
6543            throw new IllegalArgumentException("Invalid component " + admin
6544                    + " for device owner");
6545        }
6546        final boolean hasIncompatibleAccountsOrNonAdb =
6547                hasIncompatibleAccountsOrNonAdbNoLock(userId, admin);
6548        synchronized (this) {
6549            enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb);
6550            final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
6551            if (activeAdmin == null
6552                    || getUserData(userId).mRemovingAdmins.contains(admin)) {
6553                throw new IllegalArgumentException("Not active admin: " + admin);
6554            }
6555
6556            // Shutting down backup manager service permanently.
6557            long ident = mInjector.binderClearCallingIdentity();
6558            try {
6559                if (mInjector.getIBackupManager() != null) {
6560                    mInjector.getIBackupManager()
6561                            .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
6562                }
6563            } catch (RemoteException e) {
6564                throw new IllegalStateException("Failed deactivating backup service.", e);
6565            } finally {
6566                mInjector.binderRestoreCallingIdentity(ident);
6567            }
6568
6569            if (isAdb()) {
6570                // Log device owner provisioning was started using adb.
6571                MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
6572            }
6573
6574            mOwners.setDeviceOwner(admin, ownerName, userId);
6575            mOwners.writeDeviceOwner();
6576            updateDeviceOwnerLocked();
6577            setDeviceOwnerSystemPropertyLocked();
6578
6579            final Set<String> restrictions =
6580                    UserRestrictionsUtils.getDefaultEnabledForDeviceOwner();
6581            if (!restrictions.isEmpty()) {
6582                for (String restriction : restrictions) {
6583                    activeAdmin.ensureUserRestrictions().putBoolean(restriction, true);
6584                }
6585                activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions);
6586                Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions);
6587
6588                saveUserRestrictionsLocked(userId);
6589            }
6590
6591            ident = mInjector.binderClearCallingIdentity();
6592            try {
6593                // TODO Send to system too?
6594                mContext.sendBroadcastAsUser(
6595                        new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED)
6596                                .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND),
6597                        UserHandle.of(userId));
6598            } finally {
6599                mInjector.binderRestoreCallingIdentity(ident);
6600            }
6601            mDeviceAdminServiceController.startServiceForOwner(
6602                    admin.getPackageName(), userId, "set-device-owner");
6603
6604            Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
6605            return true;
6606        }
6607    }
6608
6609    @Override
6610    public boolean hasDeviceOwner() {
6611        enforceDeviceOwnerOrManageUsers();
6612        return mOwners.hasDeviceOwner();
6613    }
6614
6615    boolean isDeviceOwner(ActiveAdmin admin) {
6616        return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
6617    }
6618
6619    public boolean isDeviceOwner(ComponentName who, int userId) {
6620        synchronized (this) {
6621            return mOwners.hasDeviceOwner()
6622                    && mOwners.getDeviceOwnerUserId() == userId
6623                    && mOwners.getDeviceOwnerComponent().equals(who);
6624        }
6625    }
6626
6627    private boolean isDeviceOwnerPackage(String packageName, int userId) {
6628        synchronized (this) {
6629            return mOwners.hasDeviceOwner()
6630                    && mOwners.getDeviceOwnerUserId() == userId
6631                    && mOwners.getDeviceOwnerPackageName().equals(packageName);
6632        }
6633    }
6634
6635    private boolean isProfileOwnerPackage(String packageName, int userId) {
6636        synchronized (this) {
6637            return mOwners.hasProfileOwner(userId)
6638                    && mOwners.getProfileOwnerPackage(userId).equals(packageName);
6639        }
6640    }
6641
6642    public boolean isProfileOwner(ComponentName who, int userId) {
6643        final ComponentName profileOwner = getProfileOwner(userId);
6644        return who != null && who.equals(profileOwner);
6645    }
6646
6647    @Override
6648    public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
6649        if (!mHasFeature) {
6650            return null;
6651        }
6652        if (!callingUserOnly) {
6653            enforceManageUsers();
6654        }
6655        synchronized (this) {
6656            if (!mOwners.hasDeviceOwner()) {
6657                return null;
6658            }
6659            if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
6660                    mOwners.getDeviceOwnerUserId()) {
6661                return null;
6662            }
6663            return mOwners.getDeviceOwnerComponent();
6664        }
6665    }
6666
6667    @Override
6668    public int getDeviceOwnerUserId() {
6669        if (!mHasFeature) {
6670            return UserHandle.USER_NULL;
6671        }
6672        enforceManageUsers();
6673        synchronized (this) {
6674            return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
6675        }
6676    }
6677
6678    /**
6679     * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
6680     * MANAGE_USERS.
6681     */
6682    @Override
6683    public String getDeviceOwnerName() {
6684        if (!mHasFeature) {
6685            return null;
6686        }
6687        enforceManageUsers();
6688        synchronized (this) {
6689            if (!mOwners.hasDeviceOwner()) {
6690                return null;
6691            }
6692            // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
6693            // Should setDeviceOwner/ProfileOwner still take a name?
6694            String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
6695            return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
6696        }
6697    }
6698
6699    /** Returns the active device owner or {@code null} if there is no device owner. */
6700    @VisibleForTesting
6701    ActiveAdmin getDeviceOwnerAdminLocked() {
6702        ComponentName component = mOwners.getDeviceOwnerComponent();
6703        if (component == null) {
6704            return null;
6705        }
6706
6707        DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
6708        final int n = policy.mAdminList.size();
6709        for (int i = 0; i < n; i++) {
6710            ActiveAdmin admin = policy.mAdminList.get(i);
6711            if (component.equals(admin.info.getComponent())) {
6712                return admin;
6713            }
6714        }
6715        Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
6716        return null;
6717    }
6718
6719    @Override
6720    public void clearDeviceOwner(String packageName) {
6721        Preconditions.checkNotNull(packageName, "packageName is null");
6722        final int callingUid = mInjector.binderGetCallingUid();
6723        try {
6724            int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName,
6725                    UserHandle.getUserId(callingUid));
6726            if (uid != callingUid) {
6727                throw new SecurityException("Invalid packageName");
6728            }
6729        } catch (NameNotFoundException e) {
6730            throw new SecurityException(e);
6731        }
6732        synchronized (this) {
6733            final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6734            final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6735            if (!mOwners.hasDeviceOwner()
6736                    || !deviceOwnerComponent.getPackageName().equals(packageName)
6737                    || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
6738                throw new SecurityException(
6739                        "clearDeviceOwner can only be called by the device owner");
6740            }
6741            enforceUserUnlocked(deviceOwnerUserId);
6742
6743            final ActiveAdmin admin = getDeviceOwnerAdminLocked();
6744            long ident = mInjector.binderClearCallingIdentity();
6745            try {
6746                clearDeviceOwnerLocked(admin, deviceOwnerUserId);
6747                removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
6748                Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
6749                intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
6750                mContext.sendBroadcastAsUser(intent, UserHandle.of(deviceOwnerUserId));
6751            } finally {
6752                mInjector.binderRestoreCallingIdentity(ident);
6753            }
6754            Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
6755        }
6756    }
6757
6758    private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
6759        mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner");
6760
6761        if (admin != null) {
6762            admin.disableCamera = false;
6763            admin.userRestrictions = null;
6764            admin.defaultEnabledRestrictionsAlreadySet.clear();
6765            admin.forceEphemeralUsers = false;
6766            admin.isNetworkLoggingEnabled = false;
6767            mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
6768        }
6769        final DevicePolicyData policyData = getUserData(userId);
6770        policyData.mCurrentInputMethodSet = false;
6771        saveSettingsLocked(userId);
6772        final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM);
6773        systemPolicyData.mLastSecurityLogRetrievalTime = -1;
6774        systemPolicyData.mLastBugReportRequestTime = -1;
6775        systemPolicyData.mLastNetworkLogsRetrievalTime = -1;
6776        saveSettingsLocked(UserHandle.USER_SYSTEM);
6777        clearUserPoliciesLocked(userId);
6778
6779        mOwners.clearDeviceOwner();
6780        mOwners.writeDeviceOwner();
6781        updateDeviceOwnerLocked();
6782
6783        clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId));
6784        mInjector.securityLogSetLoggingEnabledProperty(false);
6785        mSecurityLogMonitor.stop();
6786        setNetworkLoggingActiveInternal(false);
6787
6788        try {
6789            if (mInjector.getIBackupManager() != null) {
6790                // Reactivate backup service.
6791                mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6792            }
6793        } catch (RemoteException e) {
6794            throw new IllegalStateException("Failed reactivating backup service.", e);
6795        }
6796    }
6797
6798    @Override
6799    public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6800        if (!mHasFeature) {
6801            return false;
6802        }
6803        if (who == null
6804                || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6805            throw new IllegalArgumentException("Component " + who
6806                    + " not installed for userId:" + userHandle);
6807        }
6808        final boolean hasIncompatibleAccountsOrNonAdb =
6809                hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who);
6810        synchronized (this) {
6811            enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb);
6812
6813            final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6814            if (admin == null || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6815                throw new IllegalArgumentException("Not active admin: " + who);
6816            }
6817
6818            if (isAdb()) {
6819                // Log profile owner provisioning was started using adb.
6820                MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
6821            }
6822
6823            mOwners.setProfileOwner(who, ownerName, userHandle);
6824            mOwners.writeProfileOwner(userHandle);
6825            Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6826
6827            final long id = mInjector.binderClearCallingIdentity();
6828            try {
6829                if (mUserManager.isManagedProfile(userHandle)) {
6830                    maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin,
6831                            UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
6832                    ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin,
6833                            true /* newOwner */);
6834                }
6835            } finally {
6836                mInjector.binderRestoreCallingIdentity(id);
6837            }
6838            mDeviceAdminServiceController.startServiceForOwner(
6839                    who.getPackageName(), userHandle, "set-profile-owner");
6840            return true;
6841        }
6842    }
6843
6844    @Override
6845    public void clearProfileOwner(ComponentName who) {
6846        if (!mHasFeature) {
6847            return;
6848        }
6849        Preconditions.checkNotNull(who, "ComponentName is null");
6850
6851        final int userId = mInjector.userHandleGetCallingUserId();
6852        enforceNotManagedProfile(userId, "clear profile owner");
6853        enforceUserUnlocked(userId);
6854        synchronized (this) {
6855            // Check if this is the profile owner who is calling
6856            final ActiveAdmin admin =
6857                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6858
6859            final long ident = mInjector.binderClearCallingIdentity();
6860            try {
6861                clearProfileOwnerLocked(admin, userId);
6862                removeActiveAdminLocked(who, userId);
6863            } finally {
6864                mInjector.binderRestoreCallingIdentity(ident);
6865            }
6866            Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6867        }
6868    }
6869
6870    public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6871        mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner");
6872
6873        if (admin != null) {
6874            admin.disableCamera = false;
6875            admin.userRestrictions = null;
6876            admin.defaultEnabledRestrictionsAlreadySet.clear();
6877        }
6878        final DevicePolicyData policyData = getUserData(userId);
6879        policyData.mCurrentInputMethodSet = false;
6880        policyData.mOwnerInstalledCaCerts.clear();
6881        saveSettingsLocked(userId);
6882        clearUserPoliciesLocked(userId);
6883        mOwners.removeProfileOwner(userId);
6884        mOwners.writeProfileOwner(userId);
6885    }
6886
6887    @Override
6888    public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6889        Preconditions.checkNotNull(who, "ComponentName is null");
6890        if (!mHasFeature) {
6891            return;
6892        }
6893
6894        final int userId = mInjector.userHandleGetCallingUserId();
6895        synchronized (this) {
6896            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6897            if (!isUserAffiliatedWithDeviceLocked(userId)) {
6898                throw new SecurityException("Admin " + who +
6899                        " is neither the device owner or affiliated user's profile owner.");
6900            }
6901            long token = mInjector.binderClearCallingIdentity();
6902            try {
6903                mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6904            } finally {
6905                mInjector.binderRestoreCallingIdentity(token);
6906            }
6907        }
6908    }
6909
6910    @Override
6911    public CharSequence getDeviceOwnerLockScreenInfo() {
6912        return mLockPatternUtils.getDeviceOwnerInfo();
6913    }
6914
6915    private void clearUserPoliciesLocked(int userId) {
6916        // Reset some of the user-specific policies.
6917        final DevicePolicyData policy = getUserData(userId);
6918        policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6919        // Clear delegations.
6920        policy.mDelegationMap.clear();
6921        policy.mStatusBarDisabled = false;
6922        policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6923        policy.mAffiliationIds.clear();
6924        policy.mLockTaskPackages.clear();
6925        policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
6926        saveSettingsLocked(userId);
6927
6928        try {
6929            mIPackageManager.updatePermissionFlagsForAllApps(
6930                    PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6931                    0  /* flagValues */, userId);
6932            pushUserRestrictions(userId);
6933        } catch (RemoteException re) {
6934            // Shouldn't happen.
6935        }
6936    }
6937
6938    @Override
6939    public boolean hasUserSetupCompleted() {
6940        return hasUserSetupCompleted(UserHandle.getCallingUserId());
6941    }
6942
6943    // This checks only if the Setup Wizard has run.  Since Wear devices pair before
6944    // completing Setup Wizard, and pairing involves transferring user data, calling
6945    // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
6946    private boolean hasUserSetupCompleted(int userHandle) {
6947        if (!mHasFeature) {
6948            return true;
6949        }
6950        return getUserData(userHandle).mUserSetupComplete;
6951    }
6952
6953    private boolean hasPaired(int userHandle) {
6954        if (!mHasFeature) {
6955            return true;
6956        }
6957        return getUserData(userHandle).mPaired;
6958    }
6959
6960    @Override
6961    public int getUserProvisioningState() {
6962        if (!mHasFeature) {
6963            return DevicePolicyManager.STATE_USER_UNMANAGED;
6964        }
6965        int userHandle = mInjector.userHandleGetCallingUserId();
6966        return getUserProvisioningState(userHandle);
6967    }
6968
6969    private int getUserProvisioningState(int userHandle) {
6970        return getUserData(userHandle).mUserProvisioningState;
6971    }
6972
6973    @Override
6974    public void setUserProvisioningState(int newState, int userHandle) {
6975        if (!mHasFeature) {
6976            return;
6977        }
6978
6979        if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6980                && getManagedUserId(userHandle) == -1) {
6981            // No managed device, user or profile, so setting provisioning state makes no sense.
6982            throw new IllegalStateException("Not allowed to change provisioning state unless a "
6983                      + "device or profile owner is set.");
6984        }
6985
6986        synchronized (this) {
6987            boolean transitionCheckNeeded = true;
6988
6989            // Calling identity/permission checks.
6990            if (isAdb()) {
6991                // ADB shell can only move directly from un-managed to finalized as part of directly
6992                // setting profile-owner or device-owner.
6993                if (getUserProvisioningState(userHandle) !=
6994                        DevicePolicyManager.STATE_USER_UNMANAGED
6995                        || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6996                    throw new IllegalStateException("Not allowed to change provisioning state "
6997                            + "unless current provisioning state is unmanaged, and new state is "
6998                            + "finalized.");
6999                }
7000                transitionCheckNeeded = false;
7001            } else {
7002                // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
7003                enforceCanManageProfileAndDeviceOwners();
7004            }
7005
7006            final DevicePolicyData policyData = getUserData(userHandle);
7007            if (transitionCheckNeeded) {
7008                // Optional state transition check for non-ADB case.
7009                checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
7010            }
7011            policyData.mUserProvisioningState = newState;
7012            saveSettingsLocked(userHandle);
7013        }
7014    }
7015
7016    private void checkUserProvisioningStateTransition(int currentState, int newState) {
7017        // Valid transitions for normal use-cases.
7018        switch (currentState) {
7019            case DevicePolicyManager.STATE_USER_UNMANAGED:
7020                // Can move to any state from unmanaged (except itself as an edge case)..
7021                if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
7022                    return;
7023                }
7024                break;
7025            case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
7026            case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
7027                // Can only move to finalized from these states.
7028                if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
7029                    return;
7030                }
7031                break;
7032            case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
7033                // Current user has a managed-profile, but current user is not managed, so
7034                // rather than moving to finalized state, go back to unmanaged once
7035                // profile provisioning is complete.
7036                if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
7037                    return;
7038                }
7039                break;
7040            case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
7041                // Cannot transition out of finalized.
7042                break;
7043        }
7044
7045        // Didn't meet any of the accepted state transition checks above, throw appropriate error.
7046        throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
7047                + "from state [" + currentState + "]");
7048    }
7049
7050    @Override
7051    public void setProfileEnabled(ComponentName who) {
7052        if (!mHasFeature) {
7053            return;
7054        }
7055        Preconditions.checkNotNull(who, "ComponentName is null");
7056        synchronized (this) {
7057            // Check if this is the profile owner who is calling
7058            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7059            final int userId = UserHandle.getCallingUserId();
7060            enforceManagedProfile(userId, "enable the profile");
7061            // Check if the profile is already enabled.
7062            UserInfo managedProfile = getUserInfo(userId);
7063            if (managedProfile.isEnabled()) {
7064                Slog.e(LOG_TAG,
7065                        "setProfileEnabled is called when the profile is already enabled");
7066                return;
7067            }
7068            long id = mInjector.binderClearCallingIdentity();
7069            try {
7070                mUserManager.setUserEnabled(userId);
7071                UserInfo parent = mUserManager.getProfileParent(userId);
7072                Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
7073                intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
7074                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
7075                        Intent.FLAG_RECEIVER_FOREGROUND);
7076                mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
7077            } finally {
7078                mInjector.binderRestoreCallingIdentity(id);
7079            }
7080        }
7081    }
7082
7083    @Override
7084    public void setProfileName(ComponentName who, String profileName) {
7085        Preconditions.checkNotNull(who, "ComponentName is null");
7086        int userId = UserHandle.getCallingUserId();
7087        // Check if this is the profile owner (includes device owner).
7088        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7089
7090        long id = mInjector.binderClearCallingIdentity();
7091        try {
7092            mUserManager.setUserName(userId, profileName);
7093        } finally {
7094            mInjector.binderRestoreCallingIdentity(id);
7095        }
7096    }
7097
7098    @Override
7099    public ComponentName getProfileOwner(int userHandle) {
7100        if (!mHasFeature) {
7101            return null;
7102        }
7103
7104        synchronized (this) {
7105            return mOwners.getProfileOwnerComponent(userHandle);
7106        }
7107    }
7108
7109    // Returns the active profile owner for this user or null if the current user has no
7110    // profile owner.
7111    @VisibleForTesting
7112    ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
7113        ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
7114        if (profileOwner == null) {
7115            return null;
7116        }
7117        DevicePolicyData policy = getUserData(userHandle);
7118        final int n = policy.mAdminList.size();
7119        for (int i = 0; i < n; i++) {
7120            ActiveAdmin admin = policy.mAdminList.get(i);
7121            if (profileOwner.equals(admin.info.getComponent())) {
7122                return admin;
7123            }
7124        }
7125        return null;
7126    }
7127
7128    @Override
7129    public String getProfileOwnerName(int userHandle) {
7130        if (!mHasFeature) {
7131            return null;
7132        }
7133        enforceManageUsers();
7134        ComponentName profileOwner = getProfileOwner(userHandle);
7135        if (profileOwner == null) {
7136            return null;
7137        }
7138        return getApplicationLabel(profileOwner.getPackageName(), userHandle);
7139    }
7140
7141    /**
7142     * Canonical name for a given package.
7143     */
7144    private String getApplicationLabel(String packageName, int userHandle) {
7145        long token = mInjector.binderClearCallingIdentity();
7146        try {
7147            final Context userContext;
7148            try {
7149                UserHandle handle = new UserHandle(userHandle);
7150                userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
7151            } catch (PackageManager.NameNotFoundException nnfe) {
7152                Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
7153                return null;
7154            }
7155            ApplicationInfo appInfo = userContext.getApplicationInfo();
7156            CharSequence result = null;
7157            if (appInfo != null) {
7158                PackageManager pm = userContext.getPackageManager();
7159                result = pm.getApplicationLabel(appInfo);
7160            }
7161            return result != null ? result.toString() : null;
7162        } finally {
7163            mInjector.binderRestoreCallingIdentity(token);
7164        }
7165    }
7166
7167    /**
7168     * Calls wtfStack() if called with the DPMS lock held.
7169     */
7170    private void wtfIfInLock() {
7171        if (Thread.holdsLock(this)) {
7172            Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
7173        }
7174    }
7175
7176    /**
7177     * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7178     * permission.
7179     * The profile owner can only be set before the user setup phase has completed,
7180     * except for:
7181     * - SYSTEM_UID
7182     * - adb unless hasIncompatibleAccountsOrNonAdb is true.
7183     */
7184    private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle,
7185            boolean hasIncompatibleAccountsOrNonAdb) {
7186        UserInfo info = getUserInfo(userHandle);
7187        if (info == null) {
7188            // User doesn't exist.
7189            throw new IllegalArgumentException(
7190                    "Attempted to set profile owner for invalid userId: " + userHandle);
7191        }
7192        if (info.isGuest()) {
7193            throw new IllegalStateException("Cannot set a profile owner on a guest");
7194        }
7195        if (mOwners.hasProfileOwner(userHandle)) {
7196            throw new IllegalStateException("Trying to set the profile owner, but profile owner "
7197                    + "is already set.");
7198        }
7199        if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
7200            throw new IllegalStateException("Trying to set the profile owner, but the user "
7201                    + "already has a device owner.");
7202        }
7203        if (isAdb()) {
7204            if ((mIsWatch || hasUserSetupCompleted(userHandle))
7205                    && hasIncompatibleAccountsOrNonAdb) {
7206                throw new IllegalStateException("Not allowed to set the profile owner because "
7207                        + "there are already some accounts on the profile");
7208            }
7209            return;
7210        }
7211        enforceCanManageProfileAndDeviceOwners();
7212        if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
7213            throw new IllegalStateException("Cannot set the profile owner on a user which is "
7214                    + "already set-up");
7215        }
7216    }
7217
7218    /**
7219     * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7220     * permission.
7221     */
7222    private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId,
7223            boolean hasIncompatibleAccountsOrNonAdb) {
7224        if (!isAdb()) {
7225            enforceCanManageProfileAndDeviceOwners();
7226        }
7227
7228        final int code = checkDeviceOwnerProvisioningPreConditionLocked(
7229                owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb);
7230        switch (code) {
7231            case CODE_OK:
7232                return;
7233            case CODE_HAS_DEVICE_OWNER:
7234                throw new IllegalStateException(
7235                        "Trying to set the device owner, but device owner is already set.");
7236            case CODE_USER_HAS_PROFILE_OWNER:
7237                throw new IllegalStateException("Trying to set the device owner, but the user "
7238                        + "already has a profile owner.");
7239            case CODE_USER_NOT_RUNNING:
7240                throw new IllegalStateException("User not running: " + userId);
7241            case CODE_NOT_SYSTEM_USER:
7242                throw new IllegalStateException("User is not system user");
7243            case CODE_USER_SETUP_COMPLETED:
7244                throw new IllegalStateException(
7245                        "Cannot set the device owner if the device is already set-up");
7246            case CODE_NONSYSTEM_USER_EXISTS:
7247                throw new IllegalStateException("Not allowed to set the device owner because there "
7248                        + "are already several users on the device");
7249            case CODE_ACCOUNTS_NOT_EMPTY:
7250                throw new IllegalStateException("Not allowed to set the device owner because there "
7251                        + "are already some accounts on the device");
7252            case CODE_HAS_PAIRED:
7253                throw new IllegalStateException("Not allowed to set the device owner because this "
7254                        + "device has already paired");
7255            default:
7256                throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code);
7257        }
7258    }
7259
7260    private void enforceUserUnlocked(int userId) {
7261        // Since we're doing this operation on behalf of an app, we only
7262        // want to use the actual "unlocked" state.
7263        Preconditions.checkState(mUserManager.isUserUnlocked(userId),
7264                "User must be running and unlocked");
7265    }
7266
7267    private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
7268        if (parent) {
7269            enforceUserUnlocked(getProfileParentId(userId));
7270        } else {
7271            enforceUserUnlocked(userId);
7272        }
7273    }
7274
7275    private void enforceManageUsers() {
7276        final int callingUid = mInjector.binderGetCallingUid();
7277        if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
7278            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7279        }
7280    }
7281
7282    private void enforceFullCrossUsersPermission(int userHandle) {
7283        enforceSystemUserOrPermissionIfCrossUser(userHandle,
7284                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
7285    }
7286
7287    private void enforceCrossUsersPermission(int userHandle) {
7288        enforceSystemUserOrPermissionIfCrossUser(userHandle,
7289                android.Manifest.permission.INTERACT_ACROSS_USERS);
7290    }
7291
7292    private void enforceSystemUserOrPermission(String permission) {
7293        if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) {
7294            mContext.enforceCallingOrSelfPermission(permission,
7295                    "Must be system or have " + permission + " permission");
7296        }
7297    }
7298
7299    private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) {
7300        if (userHandle < 0) {
7301            throw new IllegalArgumentException("Invalid userId " + userHandle);
7302        }
7303        if (userHandle == mInjector.userHandleGetCallingUserId()) {
7304            return;
7305        }
7306        enforceSystemUserOrPermission(permission);
7307    }
7308
7309    private void enforceManagedProfile(int userHandle, String message) {
7310        if(!isManagedProfile(userHandle)) {
7311            throw new SecurityException("You can not " + message + " outside a managed profile.");
7312        }
7313    }
7314
7315    private void enforceNotManagedProfile(int userHandle, String message) {
7316        if(isManagedProfile(userHandle)) {
7317            throw new SecurityException("You can not " + message + " for a managed profile.");
7318        }
7319    }
7320
7321    private void enforceDeviceOwnerOrManageUsers() {
7322        synchronized (this) {
7323            if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7324                    mInjector.binderGetCallingUid()) != null) {
7325                return;
7326            }
7327        }
7328        enforceManageUsers();
7329    }
7330
7331    private void enforceProfileOwnerOrSystemUser() {
7332        synchronized (this) {
7333            if (getActiveAdminWithPolicyForUidLocked(null,
7334                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7335                            != null) {
7336                return;
7337            }
7338        }
7339        Preconditions.checkState(isCallerWithSystemUid(),
7340                "Only profile owner, device owner and system may call this method.");
7341    }
7342
7343    private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) {
7344        if (userId == mInjector.userHandleGetCallingUserId()) {
7345            synchronized (this) {
7346                if (getActiveAdminWithPolicyForUidLocked(null,
7347                        DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7348                                != null) {
7349                    // Device Owner/Profile Owner may access the user it runs on.
7350                    return;
7351                }
7352            }
7353        }
7354        // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required.
7355        enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
7356    }
7357
7358    private void ensureCallerPackage(@Nullable String packageName) {
7359        if (packageName == null) {
7360            Preconditions.checkState(isCallerWithSystemUid(),
7361                    "Only caller can omit package name");
7362        } else {
7363            final int callingUid = mInjector.binderGetCallingUid();
7364            final int userId = mInjector.userHandleGetCallingUserId();
7365            try {
7366                final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
7367                        packageName, 0, userId);
7368                Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
7369            } catch (RemoteException e) {
7370                // Shouldn't happen
7371            }
7372        }
7373    }
7374
7375    private boolean isCallerWithSystemUid() {
7376        return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
7377    }
7378
7379    protected int getProfileParentId(int userHandle) {
7380        final long ident = mInjector.binderClearCallingIdentity();
7381        try {
7382            UserInfo parentUser = mUserManager.getProfileParent(userHandle);
7383            return parentUser != null ? parentUser.id : userHandle;
7384        } finally {
7385            mInjector.binderRestoreCallingIdentity(ident);
7386        }
7387    }
7388
7389    private int getCredentialOwner(int userHandle, boolean parent) {
7390        final long ident = mInjector.binderClearCallingIdentity();
7391        try {
7392            if (parent) {
7393                UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
7394                if (parentProfile != null) {
7395                    userHandle = parentProfile.id;
7396                }
7397            }
7398            return mUserManager.getCredentialOwnerProfile(userHandle);
7399        } finally {
7400            mInjector.binderRestoreCallingIdentity(ident);
7401        }
7402    }
7403
7404    private boolean isManagedProfile(int userHandle) {
7405        final UserInfo user = getUserInfo(userHandle);
7406        return user != null && user.isManagedProfile();
7407    }
7408
7409    private void enableIfNecessary(String packageName, int userId) {
7410        try {
7411            final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
7412                    PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId);
7413            if (ai.enabledSetting
7414                    == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
7415                mIPackageManager.setApplicationEnabledSetting(packageName,
7416                        PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
7417                        PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
7418            }
7419        } catch (RemoteException e) {
7420        }
7421    }
7422
7423    @Override
7424    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7425        if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
7426
7427        synchronized (this) {
7428            pw.println("Current Device Policy Manager state:");
7429
7430            mOwners.dump("  ", pw);
7431            mDeviceAdminServiceController.dump("  ", pw);
7432            int userCount = mUserData.size();
7433            for (int u = 0; u < userCount; u++) {
7434                DevicePolicyData policy = getUserData(mUserData.keyAt(u));
7435                pw.println();
7436                pw.println("  Enabled Device Admins (User " + policy.mUserHandle
7437                        + ", provisioningState: " + policy.mUserProvisioningState + "):");
7438                final int N = policy.mAdminList.size();
7439                for (int i=0; i<N; i++) {
7440                    ActiveAdmin ap = policy.mAdminList.get(i);
7441                    if (ap != null) {
7442                        pw.print("    "); pw.print(ap.info.getComponent().flattenToShortString());
7443                                pw.println(":");
7444                        ap.dump("      ", pw);
7445                    }
7446                }
7447                if (!policy.mRemovingAdmins.isEmpty()) {
7448                    pw.println("    Removing Device Admins (User " + policy.mUserHandle + "): "
7449                            + policy.mRemovingAdmins);
7450                }
7451
7452                pw.println(" ");
7453                pw.print("    mPasswordOwner="); pw.println(policy.mPasswordOwner);
7454            }
7455            pw.println();
7456            mConstants.dump("  ", pw);
7457            pw.println();
7458            pw.println("  Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
7459        }
7460    }
7461
7462    private String getEncryptionStatusName(int encryptionStatus) {
7463        switch (encryptionStatus) {
7464            case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
7465                return "inactive";
7466            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
7467                return "block default key";
7468            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
7469                return "block";
7470            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
7471                return "per-user";
7472            case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
7473                return "unsupported";
7474            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
7475                return "activating";
7476            default:
7477                return "unknown";
7478        }
7479    }
7480
7481    @Override
7482    public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
7483            ComponentName activity) {
7484        Preconditions.checkNotNull(who, "ComponentName is null");
7485        final int userHandle = UserHandle.getCallingUserId();
7486        synchronized (this) {
7487            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7488
7489            long id = mInjector.binderClearCallingIdentity();
7490            try {
7491                mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
7492                mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
7493            } catch (RemoteException re) {
7494                // Shouldn't happen
7495            } finally {
7496                mInjector.binderRestoreCallingIdentity(id);
7497            }
7498        }
7499    }
7500
7501    @Override
7502    public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
7503        Preconditions.checkNotNull(who, "ComponentName is null");
7504        final int userHandle = UserHandle.getCallingUserId();
7505        synchronized (this) {
7506            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7507
7508            long id = mInjector.binderClearCallingIdentity();
7509            try {
7510                mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
7511                mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
7512            } catch (RemoteException re) {
7513                // Shouldn't happen
7514            } finally {
7515                mInjector.binderRestoreCallingIdentity(id);
7516            }
7517        }
7518    }
7519
7520    @Override
7521    public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
7522            String packageName) {
7523        try {
7524            setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
7525        } catch (IllegalArgumentException e) {
7526            return false;
7527        }
7528        return true;
7529    }
7530
7531    @Override
7532    public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
7533        final List<String> delegatePackages = getDelegatePackages(admin,
7534                DELEGATION_APP_RESTRICTIONS);
7535        return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
7536    }
7537
7538    @Override
7539    public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
7540        return isCallerDelegate(callerPackage, DELEGATION_APP_RESTRICTIONS);
7541    }
7542
7543    @Override
7544    public void setApplicationRestrictions(ComponentName who, String callerPackage,
7545            String packageName, Bundle settings) {
7546        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
7547                DELEGATION_APP_RESTRICTIONS);
7548
7549        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7550        final long id = mInjector.binderClearCallingIdentity();
7551        try {
7552            mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
7553        } finally {
7554            mInjector.binderRestoreCallingIdentity(id);
7555        }
7556    }
7557
7558    @Override
7559    public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
7560            PersistableBundle args, boolean parent) {
7561        if (!mHasFeature) {
7562            return;
7563        }
7564        Preconditions.checkNotNull(admin, "admin is null");
7565        Preconditions.checkNotNull(agent, "agent is null");
7566        final int userHandle = UserHandle.getCallingUserId();
7567        synchronized (this) {
7568            ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
7569                    DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
7570            ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
7571            saveSettingsLocked(userHandle);
7572        }
7573    }
7574
7575    @Override
7576    public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
7577            ComponentName agent, int userHandle, boolean parent) {
7578        if (!mHasFeature) {
7579            return null;
7580        }
7581        Preconditions.checkNotNull(agent, "agent null");
7582        enforceFullCrossUsersPermission(userHandle);
7583
7584        synchronized (this) {
7585            final String componentName = agent.flattenToString();
7586            if (admin != null) {
7587                final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
7588                if (ap == null) return null;
7589                TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
7590                if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
7591                List<PersistableBundle> result = new ArrayList<>();
7592                result.add(trustAgentInfo.options);
7593                return result;
7594            }
7595
7596            // Return strictest policy for this user and profiles that are visible from this user.
7597            List<PersistableBundle> result = null;
7598            // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
7599            // of the options. If any admin doesn't have options, discard options for the rest
7600            // and return null.
7601            List<ActiveAdmin> admins =
7602                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
7603            boolean allAdminsHaveOptions = true;
7604            final int N = admins.size();
7605            for (int i = 0; i < N; i++) {
7606                final ActiveAdmin active = admins.get(i);
7607
7608                final boolean disablesTrust = (active.disabledKeyguardFeatures
7609                        & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
7610                final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
7611                if (info != null && info.options != null && !info.options.isEmpty()) {
7612                    if (disablesTrust) {
7613                        if (result == null) {
7614                            result = new ArrayList<>();
7615                        }
7616                        result.add(info.options);
7617                    } else {
7618                        Log.w(LOG_TAG, "Ignoring admin " + active.info
7619                                + " because it has trust options but doesn't declare "
7620                                + "KEYGUARD_DISABLE_TRUST_AGENTS");
7621                    }
7622                } else if (disablesTrust) {
7623                    allAdminsHaveOptions = false;
7624                    break;
7625                }
7626            }
7627            return allAdminsHaveOptions ? result : null;
7628        }
7629    }
7630
7631    @Override
7632    public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
7633        Preconditions.checkNotNull(who, "ComponentName is null");
7634        synchronized (this) {
7635            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7636
7637            int userHandle = UserHandle.getCallingUserId();
7638            DevicePolicyData userData = getUserData(userHandle);
7639            userData.mRestrictionsProvider = permissionProvider;
7640            saveSettingsLocked(userHandle);
7641        }
7642    }
7643
7644    @Override
7645    public ComponentName getRestrictionsProvider(int userHandle) {
7646        synchronized (this) {
7647            if (!isCallerWithSystemUid()) {
7648                throw new SecurityException("Only the system can query the permission provider");
7649            }
7650            DevicePolicyData userData = getUserData(userHandle);
7651            return userData != null ? userData.mRestrictionsProvider : null;
7652        }
7653    }
7654
7655    @Override
7656    public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
7657        Preconditions.checkNotNull(who, "ComponentName is null");
7658        int callingUserId = UserHandle.getCallingUserId();
7659        synchronized (this) {
7660            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7661
7662            long id = mInjector.binderClearCallingIdentity();
7663            try {
7664                UserInfo parent = mUserManager.getProfileParent(callingUserId);
7665                if (parent == null) {
7666                    Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
7667                            + "parent");
7668                    return;
7669                }
7670                if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
7671                    mIPackageManager.addCrossProfileIntentFilter(
7672                            filter, who.getPackageName(), callingUserId, parent.id, 0);
7673                }
7674                if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
7675                    mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
7676                            parent.id, callingUserId, 0);
7677                }
7678            } catch (RemoteException re) {
7679                // Shouldn't happen
7680            } finally {
7681                mInjector.binderRestoreCallingIdentity(id);
7682            }
7683        }
7684    }
7685
7686    @Override
7687    public void clearCrossProfileIntentFilters(ComponentName who) {
7688        Preconditions.checkNotNull(who, "ComponentName is null");
7689        int callingUserId = UserHandle.getCallingUserId();
7690        synchronized (this) {
7691            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7692            long id = mInjector.binderClearCallingIdentity();
7693            try {
7694                UserInfo parent = mUserManager.getProfileParent(callingUserId);
7695                if (parent == null) {
7696                    Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
7697                            + "parent");
7698                    return;
7699                }
7700                // Removing those that go from the managed profile to the parent.
7701                mIPackageManager.clearCrossProfileIntentFilters(
7702                        callingUserId, who.getPackageName());
7703                // And those that go from the parent to the managed profile.
7704                // If we want to support multiple managed profiles, we will have to only remove
7705                // those that have callingUserId as their target.
7706                mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
7707            } catch (RemoteException re) {
7708                // Shouldn't happen
7709            } finally {
7710                mInjector.binderRestoreCallingIdentity(id);
7711            }
7712        }
7713    }
7714
7715    /**
7716     * @return true if all packages in enabledPackages are either in the list
7717     * permittedList or are a system app.
7718     */
7719    private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
7720            List<String> permittedList, int userIdToCheck) {
7721        long id = mInjector.binderClearCallingIdentity();
7722        try {
7723            // If we have an enabled packages list for a managed profile the packages
7724            // we should check are installed for the parent user.
7725            UserInfo user = getUserInfo(userIdToCheck);
7726            if (user.isManagedProfile()) {
7727                userIdToCheck = user.profileGroupId;
7728            }
7729
7730            for (String enabledPackage : enabledPackages) {
7731                boolean systemService = false;
7732                try {
7733                    ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
7734                            enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
7735                            userIdToCheck);
7736                    systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7737                } catch (RemoteException e) {
7738                    Log.i(LOG_TAG, "Can't talk to package managed", e);
7739                }
7740                if (!systemService && !permittedList.contains(enabledPackage)) {
7741                    return false;
7742                }
7743            }
7744        } finally {
7745            mInjector.binderRestoreCallingIdentity(id);
7746        }
7747        return true;
7748    }
7749
7750    private AccessibilityManager getAccessibilityManagerForUser(int userId) {
7751        // Not using AccessibilityManager.getInstance because that guesses
7752        // at the user you require based on callingUid and caches for a given
7753        // process.
7754        IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
7755        IAccessibilityManager service = iBinder == null
7756                ? null : IAccessibilityManager.Stub.asInterface(iBinder);
7757        return new AccessibilityManager(mContext, service, userId);
7758    }
7759
7760    @Override
7761    public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
7762        if (!mHasFeature) {
7763            return false;
7764        }
7765        Preconditions.checkNotNull(who, "ComponentName is null");
7766
7767        if (packageList != null) {
7768            int userId = UserHandle.getCallingUserId();
7769            List<AccessibilityServiceInfo> enabledServices = null;
7770            long id = mInjector.binderClearCallingIdentity();
7771            try {
7772                UserInfo user = getUserInfo(userId);
7773                if (user.isManagedProfile()) {
7774                    userId = user.profileGroupId;
7775                }
7776                AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
7777                enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
7778                        AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
7779            } finally {
7780                mInjector.binderRestoreCallingIdentity(id);
7781            }
7782
7783            if (enabledServices != null) {
7784                List<String> enabledPackages = new ArrayList<String>();
7785                for (AccessibilityServiceInfo service : enabledServices) {
7786                    enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
7787                }
7788                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7789                        userId)) {
7790                    Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
7791                            + "because it contains already enabled accesibility services.");
7792                    return false;
7793                }
7794            }
7795        }
7796
7797        synchronized (this) {
7798            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7799                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7800            admin.permittedAccessiblityServices = packageList;
7801            saveSettingsLocked(UserHandle.getCallingUserId());
7802        }
7803        return true;
7804    }
7805
7806    @Override
7807    public List getPermittedAccessibilityServices(ComponentName who) {
7808        if (!mHasFeature) {
7809            return null;
7810        }
7811        Preconditions.checkNotNull(who, "ComponentName is null");
7812
7813        synchronized (this) {
7814            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7815                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7816            return admin.permittedAccessiblityServices;
7817        }
7818    }
7819
7820    @Override
7821    public List getPermittedAccessibilityServicesForUser(int userId) {
7822        if (!mHasFeature) {
7823            return null;
7824        }
7825        synchronized (this) {
7826            List<String> result = null;
7827            // If we have multiple profiles we return the intersection of the
7828            // permitted lists. This can happen in cases where we have a device
7829            // and profile owner.
7830            int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7831            for (int profileId : profileIds) {
7832                // Just loop though all admins, only device or profiles
7833                // owners can have permitted lists set.
7834                DevicePolicyData policy = getUserDataUnchecked(profileId);
7835                final int N = policy.mAdminList.size();
7836                for (int j = 0; j < N; j++) {
7837                    ActiveAdmin admin = policy.mAdminList.get(j);
7838                    List<String> fromAdmin = admin.permittedAccessiblityServices;
7839                    if (fromAdmin != null) {
7840                        if (result == null) {
7841                            result = new ArrayList<>(fromAdmin);
7842                        } else {
7843                            result.retainAll(fromAdmin);
7844                        }
7845                    }
7846                }
7847            }
7848
7849            // If we have a permitted list add all system accessibility services.
7850            if (result != null) {
7851                long id = mInjector.binderClearCallingIdentity();
7852                try {
7853                    UserInfo user = getUserInfo(userId);
7854                    if (user.isManagedProfile()) {
7855                        userId = user.profileGroupId;
7856                    }
7857                    AccessibilityManager accessibilityManager =
7858                            getAccessibilityManagerForUser(userId);
7859                    List<AccessibilityServiceInfo> installedServices =
7860                            accessibilityManager.getInstalledAccessibilityServiceList();
7861
7862                    if (installedServices != null) {
7863                        for (AccessibilityServiceInfo service : installedServices) {
7864                            ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7865                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7866                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7867                                result.add(serviceInfo.packageName);
7868                            }
7869                        }
7870                    }
7871                } finally {
7872                    mInjector.binderRestoreCallingIdentity(id);
7873                }
7874            }
7875
7876            return result;
7877        }
7878    }
7879
7880    @Override
7881    public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7882            int userHandle) {
7883        if (!mHasFeature) {
7884            return true;
7885        }
7886        Preconditions.checkNotNull(who, "ComponentName is null");
7887        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7888        if (!isCallerWithSystemUid()){
7889            throw new SecurityException(
7890                    "Only the system can query if an accessibility service is disabled by admin");
7891        }
7892        synchronized (this) {
7893            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7894            if (admin == null) {
7895                return false;
7896            }
7897            if (admin.permittedAccessiblityServices == null) {
7898                return true;
7899            }
7900            return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
7901                    admin.permittedAccessiblityServices, userHandle);
7902        }
7903    }
7904
7905    private boolean checkCallerIsCurrentUserOrProfile() {
7906        final int callingUserId = UserHandle.getCallingUserId();
7907        final long token = mInjector.binderClearCallingIdentity();
7908        try {
7909            UserInfo currentUser;
7910            UserInfo callingUser = getUserInfo(callingUserId);
7911            try {
7912                currentUser = mInjector.getIActivityManager().getCurrentUser();
7913            } catch (RemoteException e) {
7914                Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7915                return false;
7916            }
7917
7918            if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7919                Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7920                        + "of a user that isn't the foreground user.");
7921                return false;
7922            }
7923            if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7924                Slog.e(LOG_TAG, "Cannot set permitted input methods "
7925                        + "of a user that isn't the foreground user.");
7926                return false;
7927            }
7928        } finally {
7929            mInjector.binderRestoreCallingIdentity(token);
7930        }
7931        return true;
7932    }
7933
7934    @Override
7935    public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7936        if (!mHasFeature) {
7937            return false;
7938        }
7939        Preconditions.checkNotNull(who, "ComponentName is null");
7940
7941        // TODO When InputMethodManager supports per user calls remove
7942        //      this restriction.
7943        if (!checkCallerIsCurrentUserOrProfile()) {
7944            return false;
7945        }
7946
7947        final int callingUserId = mInjector.userHandleGetCallingUserId();
7948        if (packageList != null) {
7949            // InputMethodManager fetches input methods for current user.
7950            // So this can only be set when calling user is the current user
7951            // or parent is current user in case of managed profiles.
7952            InputMethodManager inputMethodManager =
7953                    mContext.getSystemService(InputMethodManager.class);
7954            List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7955
7956            if (enabledImes != null) {
7957                List<String> enabledPackages = new ArrayList<String>();
7958                for (InputMethodInfo ime : enabledImes) {
7959                    enabledPackages.add(ime.getPackageName());
7960                }
7961                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7962                        callingUserId)) {
7963                    Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7964                            + "because it contains already enabled input method.");
7965                    return false;
7966                }
7967            }
7968        }
7969
7970        synchronized (this) {
7971            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7972                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7973            admin.permittedInputMethods = packageList;
7974            saveSettingsLocked(callingUserId);
7975        }
7976        return true;
7977    }
7978
7979    @Override
7980    public List getPermittedInputMethods(ComponentName who) {
7981        if (!mHasFeature) {
7982            return null;
7983        }
7984        Preconditions.checkNotNull(who, "ComponentName is null");
7985
7986        synchronized (this) {
7987            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7988                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7989            return admin.permittedInputMethods;
7990        }
7991    }
7992
7993    @Override
7994    public List getPermittedInputMethodsForCurrentUser() {
7995        UserInfo currentUser;
7996        try {
7997            currentUser = mInjector.getIActivityManager().getCurrentUser();
7998        } catch (RemoteException e) {
7999            Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
8000            // Activity managed is dead, just allow all IMEs
8001            return null;
8002        }
8003
8004        int userId = currentUser.id;
8005        synchronized (this) {
8006            List<String> result = null;
8007            // If we have multiple profiles we return the intersection of the
8008            // permitted lists. This can happen in cases where we have a device
8009            // and profile owner.
8010            int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
8011            for (int profileId : profileIds) {
8012                // Just loop though all admins, only device or profiles
8013                // owners can have permitted lists set.
8014                DevicePolicyData policy = getUserDataUnchecked(profileId);
8015                final int N = policy.mAdminList.size();
8016                for (int j = 0; j < N; j++) {
8017                    ActiveAdmin admin = policy.mAdminList.get(j);
8018                    List<String> fromAdmin = admin.permittedInputMethods;
8019                    if (fromAdmin != null) {
8020                        if (result == null) {
8021                            result = new ArrayList<String>(fromAdmin);
8022                        } else {
8023                            result.retainAll(fromAdmin);
8024                        }
8025                    }
8026                }
8027            }
8028
8029            // If we have a permitted list add all system input methods.
8030            if (result != null) {
8031                InputMethodManager inputMethodManager =
8032                        mContext.getSystemService(InputMethodManager.class);
8033                List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
8034                long id = mInjector.binderClearCallingIdentity();
8035                try {
8036                    if (imes != null) {
8037                        for (InputMethodInfo ime : imes) {
8038                            ServiceInfo serviceInfo = ime.getServiceInfo();
8039                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
8040                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8041                                result.add(serviceInfo.packageName);
8042                            }
8043                        }
8044                    }
8045                } finally {
8046                    mInjector.binderRestoreCallingIdentity(id);
8047                }
8048            }
8049            return result;
8050        }
8051    }
8052
8053    @Override
8054    public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
8055            int userHandle) {
8056        if (!mHasFeature) {
8057            return true;
8058        }
8059        Preconditions.checkNotNull(who, "ComponentName is null");
8060        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
8061        if (!isCallerWithSystemUid()) {
8062            throw new SecurityException(
8063                    "Only the system can query if an input method is disabled by admin");
8064        }
8065        synchronized (this) {
8066            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8067            if (admin == null) {
8068                return false;
8069            }
8070            if (admin.permittedInputMethods == null) {
8071                return true;
8072            }
8073            return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8074                    admin.permittedInputMethods, userHandle);
8075        }
8076    }
8077
8078    @Override
8079    public boolean setPermittedCrossProfileNotificationListeners(
8080            ComponentName who, List<String> packageList) {
8081        if (!mHasFeature) {
8082            return false;
8083        }
8084        Preconditions.checkNotNull(who, "ComponentName is null");
8085
8086        final int callingUserId = mInjector.userHandleGetCallingUserId();
8087        if (!isManagedProfile(callingUserId)) {
8088            return false;
8089        }
8090
8091        synchronized (this) {
8092            ActiveAdmin admin = getActiveAdminForCallerLocked(
8093                    who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8094            admin.permittedNotificationListeners = packageList;
8095            saveSettingsLocked(callingUserId);
8096        }
8097        return true;
8098    }
8099
8100    @Override
8101    public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) {
8102        if (!mHasFeature) {
8103            return null;
8104        }
8105        Preconditions.checkNotNull(who, "ComponentName is null");
8106
8107        synchronized (this) {
8108            ActiveAdmin admin = getActiveAdminForCallerLocked(
8109                    who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8110            return admin.permittedNotificationListeners;
8111        }
8112    }
8113
8114    @Override
8115    public boolean isNotificationListenerServicePermitted(String packageName, int userId) {
8116        if (!mHasFeature) {
8117            return true;
8118        }
8119
8120        Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty");
8121        if (!isCallerWithSystemUid()) {
8122            throw new SecurityException(
8123                    "Only the system can query if a notification listener service is permitted");
8124        }
8125        synchronized (this) {
8126            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
8127            if (profileOwner == null || profileOwner.permittedNotificationListeners == null) {
8128                return true;
8129            }
8130            return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8131                    profileOwner.permittedNotificationListeners, userId);
8132
8133        }
8134    }
8135
8136    private void maybeSendAdminEnabledBroadcastLocked(int userHandle) {
8137        DevicePolicyData policyData = getUserData(userHandle);
8138        if (policyData.mAdminBroadcastPending) {
8139            // Send the initialization data to profile owner and delete the data
8140            ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
8141            boolean clearInitBundle = true;
8142            if (admin != null) {
8143                PersistableBundle initBundle = policyData.mInitBundle;
8144                clearInitBundle = sendAdminCommandLocked(admin,
8145                        DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
8146                        initBundle == null ? null : new Bundle(initBundle),
8147                        null /* result receiver */,
8148                        true /* send in foreground */);
8149            }
8150            if (clearInitBundle) {
8151                // If there's no admin or we've successfully called the admin, clear the init bundle
8152                // otherwise, keep it around
8153                policyData.mInitBundle = null;
8154                policyData.mAdminBroadcastPending = false;
8155                saveSettingsLocked(userHandle);
8156            }
8157        }
8158    }
8159
8160    @Override
8161    public UserHandle createAndManageUser(ComponentName admin, String name,
8162            ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
8163        Preconditions.checkNotNull(admin, "admin is null");
8164        Preconditions.checkNotNull(profileOwner, "profileOwner is null");
8165        if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
8166            throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
8167                    + admin + " are not in the same package");
8168        }
8169        // Only allow the system user to use this method
8170        if (!mInjector.binderGetCallingUserHandle().isSystem()) {
8171            throw new SecurityException("createAndManageUser was called from non-system user");
8172        }
8173        final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0;
8174        final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0
8175                && UserManager.isDeviceInDemoMode(mContext);
8176        final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0;
8177        // Create user.
8178        UserHandle user = null;
8179        synchronized (this) {
8180            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8181
8182            final long id = mInjector.binderClearCallingIdentity();
8183            try {
8184                int userInfoFlags = 0;
8185                if (ephemeral) {
8186                    userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
8187                }
8188                if (demo) {
8189                    userInfoFlags |= UserInfo.FLAG_DEMO;
8190                }
8191                String[] disallowedPackages = null;
8192                if (!leaveAllSystemAppsEnabled) {
8193                    disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin,
8194                            UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray(
8195                            new String[0]);
8196                }
8197                UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
8198                        userInfoFlags, disallowedPackages);
8199                if (userInfo != null) {
8200                    user = userInfo.getUserHandle();
8201                }
8202            } finally {
8203                mInjector.binderRestoreCallingIdentity(id);
8204            }
8205        }
8206        if (user == null) {
8207            return null;
8208        }
8209
8210        final int userHandle = user.getIdentifier();
8211        final Intent intent = new Intent(DevicePolicyManager.ACTION_MANAGED_USER_CREATED)
8212                .putExtra(Intent.EXTRA_USER_HANDLE, userHandle)
8213                .putExtra(
8214                        DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED,
8215                        leaveAllSystemAppsEnabled)
8216                .setPackage(MANAGED_PROVISIONING_PKG)
8217                .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8218        mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
8219
8220        final long id = mInjector.binderClearCallingIdentity();
8221        try {
8222            final String adminPkg = admin.getPackageName();
8223            try {
8224                // Install the profile owner if not present.
8225                if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
8226                    mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle,
8227                            0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8228                }
8229            } catch (RemoteException e) {
8230                // Does not happen, same process
8231            }
8232
8233            // Set admin.
8234            setActiveAdmin(profileOwner, true, userHandle);
8235            final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
8236            setProfileOwner(profileOwner, ownerName, userHandle);
8237
8238            synchronized (this) {
8239                DevicePolicyData policyData = getUserData(userHandle);
8240                policyData.mInitBundle = adminExtras;
8241                policyData.mAdminBroadcastPending = true;
8242                saveSettingsLocked(userHandle);
8243            }
8244
8245            if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
8246                Settings.Secure.putIntForUser(mContext.getContentResolver(),
8247                        Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
8248            }
8249
8250            if ((flags & START_USER_IN_BACKGROUND) != 0) {
8251                try {
8252                    mInjector.getIActivityManager().startUserInBackground(userHandle);
8253                } catch (RemoteException re) {
8254                    // Does not happen, same process
8255                }
8256            }
8257
8258            return user;
8259        } catch (Throwable re) {
8260            mUserManager.removeUser(userHandle);
8261            return null;
8262        } finally {
8263            mInjector.binderRestoreCallingIdentity(id);
8264        }
8265    }
8266
8267    @Override
8268    public boolean removeUser(ComponentName who, UserHandle userHandle) {
8269        Preconditions.checkNotNull(who, "ComponentName is null");
8270        synchronized (this) {
8271            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8272        }
8273
8274        final int callingUserId = mInjector.userHandleGetCallingUserId();
8275        final long id = mInjector.binderClearCallingIdentity();
8276        try {
8277            String restriction = isManagedProfile(userHandle.getIdentifier())
8278                    ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
8279                    : UserManager.DISALLOW_REMOVE_USER;
8280            if (isAdminAffectedByRestriction(who, restriction, callingUserId)) {
8281                Log.w(LOG_TAG, "The device owner cannot remove a user because "
8282                        + restriction + " is enabled, and was not set by the device owner");
8283                return false;
8284            }
8285            return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
8286        } finally {
8287            mInjector.binderRestoreCallingIdentity(id);
8288        }
8289    }
8290
8291    private boolean isAdminAffectedByRestriction(
8292            ComponentName admin, String userRestriction, int userId) {
8293        switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
8294            case UserManager.RESTRICTION_NOT_SET:
8295                return false;
8296            case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
8297                return !isDeviceOwner(admin, userId);
8298            case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
8299                return !isProfileOwner(admin, userId);
8300            default:
8301                return true;
8302        }
8303    }
8304
8305    @Override
8306    public boolean switchUser(ComponentName who, UserHandle userHandle) {
8307        Preconditions.checkNotNull(who, "ComponentName is null");
8308        synchronized (this) {
8309            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8310
8311            long id = mInjector.binderClearCallingIdentity();
8312            try {
8313                int userId = UserHandle.USER_SYSTEM;
8314                if (userHandle != null) {
8315                    userId = userHandle.getIdentifier();
8316                }
8317                return mInjector.getIActivityManager().switchUser(userId);
8318            } catch (RemoteException e) {
8319                Log.e(LOG_TAG, "Couldn't switch user", e);
8320                return false;
8321            } finally {
8322                mInjector.binderRestoreCallingIdentity(id);
8323            }
8324        }
8325    }
8326
8327    @Override
8328    public boolean stopUser(ComponentName who, UserHandle userHandle) {
8329        Preconditions.checkNotNull(who, "ComponentName is null");
8330
8331        synchronized (this) {
8332            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8333        }
8334
8335        final int userId = userHandle.getIdentifier();
8336        if (isManagedProfile(userId)) {
8337            Log.w(LOG_TAG, "Managed profile cannot be stopped");
8338            return false;
8339        }
8340
8341        final long id = mInjector.binderClearCallingIdentity();
8342        try {
8343            return mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)
8344                    == USER_OP_SUCCESS;
8345        } catch (RemoteException e) {
8346            // Same process, should not happen.
8347            return false;
8348        } finally {
8349            mInjector.binderRestoreCallingIdentity(id);
8350        }
8351    }
8352
8353    @Override
8354    public boolean logoutUser(ComponentName who) {
8355        Preconditions.checkNotNull(who, "ComponentName is null");
8356
8357        final int callingUserId = mInjector.userHandleGetCallingUserId();
8358        synchronized (this) {
8359            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8360            if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
8361                throw new SecurityException("Admin " + who +
8362                        " is neither the device owner or affiliated user's profile owner.");
8363            }
8364        }
8365
8366        if (isManagedProfile(callingUserId)) {
8367            Log.w(LOG_TAG, "Managed profile cannot be logout");
8368            return false;
8369        }
8370
8371        final long id = mInjector.binderClearCallingIdentity();
8372        try {
8373            if (!mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM)) {
8374                Log.w(LOG_TAG, "Failed to switch to primary user");
8375                return false;
8376            }
8377            return mInjector.getIActivityManager().stopUser(callingUserId, true /*force*/, null)
8378                    == USER_OP_SUCCESS;
8379        } catch (RemoteException e) {
8380            // Same process, should not happen.
8381            return false;
8382        } finally {
8383            mInjector.binderRestoreCallingIdentity(id);
8384        }
8385    }
8386
8387    @Override
8388    public List<UserHandle> getSecondaryUsers(ComponentName who) {
8389        Preconditions.checkNotNull(who, "ComponentName is null");
8390        synchronized (this) {
8391            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8392        }
8393
8394        final long id = mInjector.binderClearCallingIdentity();
8395        try {
8396            final List<UserInfo> userInfos = mInjector.getUserManager().getUsers(true
8397                    /*excludeDying*/);
8398            final List<UserHandle> userHandles = new ArrayList<>();
8399            for (UserInfo userInfo : userInfos) {
8400                UserHandle userHandle = userInfo.getUserHandle();
8401                if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) {
8402                    userHandles.add(userInfo.getUserHandle());
8403                }
8404            }
8405            return userHandles;
8406        } finally {
8407            mInjector.binderRestoreCallingIdentity(id);
8408        }
8409    }
8410
8411    @Override
8412    public boolean isEphemeralUser(ComponentName who) {
8413        Preconditions.checkNotNull(who, "ComponentName is null");
8414        synchronized (this) {
8415            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8416        }
8417
8418        final int callingUserId = mInjector.userHandleGetCallingUserId();
8419        final long id = mInjector.binderClearCallingIdentity();
8420        try {
8421            return mInjector.getUserManager().isUserEphemeral(callingUserId);
8422        } finally {
8423            mInjector.binderRestoreCallingIdentity(id);
8424        }
8425    }
8426
8427    @Override
8428    public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
8429            String packageName) {
8430        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8431                DELEGATION_APP_RESTRICTIONS);
8432
8433        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
8434        final long id = mInjector.binderClearCallingIdentity();
8435        try {
8436           Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
8437           // if no restrictions were saved, mUserManager.getApplicationRestrictions
8438           // returns null, but DPM method should return an empty Bundle as per JavaDoc
8439           return bundle != null ? bundle : Bundle.EMPTY;
8440        } finally {
8441            mInjector.binderRestoreCallingIdentity(id);
8442        }
8443    }
8444
8445    @Override
8446    public String[] setPackagesSuspended(ComponentName who, String callerPackage,
8447            String[] packageNames, boolean suspended) {
8448        int callingUserId = UserHandle.getCallingUserId();
8449        synchronized (this) {
8450            // Ensure the caller is a DO/PO or a package access delegate.
8451            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8452                    DELEGATION_PACKAGE_ACCESS);
8453
8454            long id = mInjector.binderClearCallingIdentity();
8455            try {
8456                return mIPackageManager.setPackagesSuspendedAsUser(
8457                        packageNames, suspended, callingUserId);
8458            } catch (RemoteException re) {
8459                // Shouldn't happen.
8460                Slog.e(LOG_TAG, "Failed talking to the package manager", re);
8461            } finally {
8462                mInjector.binderRestoreCallingIdentity(id);
8463            }
8464            return packageNames;
8465        }
8466    }
8467
8468    @Override
8469    public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
8470        int callingUserId = UserHandle.getCallingUserId();
8471        synchronized (this) {
8472            // Ensure the caller is a DO/PO or a package access delegate.
8473            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8474                    DELEGATION_PACKAGE_ACCESS);
8475
8476            long id = mInjector.binderClearCallingIdentity();
8477            try {
8478                return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
8479            } catch (RemoteException re) {
8480                // Shouldn't happen.
8481                Slog.e(LOG_TAG, "Failed talking to the package manager", re);
8482            } finally {
8483                mInjector.binderRestoreCallingIdentity(id);
8484            }
8485            return false;
8486        }
8487    }
8488
8489    @Override
8490    public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
8491        Preconditions.checkNotNull(who, "ComponentName is null");
8492        if (!UserRestrictionsUtils.isValidRestriction(key)) {
8493            return;
8494        }
8495
8496        final int userHandle = mInjector.userHandleGetCallingUserId();
8497        synchronized (this) {
8498            final ActiveAdmin activeAdmin =
8499                    getActiveAdminForCallerLocked(who,
8500                            DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8501            final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
8502            if (isDeviceOwner) {
8503                if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
8504                    throw new SecurityException("Device owner cannot set user restriction " + key);
8505                }
8506            } else { // profile owner
8507                if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
8508                    throw new SecurityException("Profile owner cannot set user restriction " + key);
8509                }
8510            }
8511
8512            // Save the restriction to ActiveAdmin.
8513            final Bundle restrictions = activeAdmin.ensureUserRestrictions();
8514            if (enabledFromThisOwner) {
8515                restrictions.putBoolean(key, true);
8516            } else {
8517                restrictions.remove(key);
8518            }
8519            saveUserRestrictionsLocked(userHandle);
8520        }
8521    }
8522
8523    private void saveUserRestrictionsLocked(int userId) {
8524        saveSettingsLocked(userId);
8525        pushUserRestrictions(userId);
8526        sendChangedNotification(userId);
8527    }
8528
8529    private void pushUserRestrictions(int userId) {
8530        synchronized (this) {
8531            final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId);
8532            final Bundle userRestrictions;
8533            // Whether device owner enforces camera restriction.
8534            boolean disallowCameraGlobally = false;
8535
8536            if (isDeviceOwner) {
8537                final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
8538                if (deviceOwner == null) {
8539                    return; // Shouldn't happen.
8540                }
8541                userRestrictions = deviceOwner.userRestrictions;
8542                // DO can disable camera globally.
8543                disallowCameraGlobally = deviceOwner.disableCamera;
8544            } else {
8545                final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
8546                userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null;
8547            }
8548
8549            // Whether any admin enforces camera restriction.
8550            final int cameraRestrictionScope =
8551                    getCameraRestrictionScopeLocked(userId, disallowCameraGlobally);
8552
8553            mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions,
8554                    isDeviceOwner, cameraRestrictionScope);
8555        }
8556    }
8557
8558    /**
8559     * Get the scope of camera restriction for a given user if any.
8560     */
8561    private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) {
8562        if (disallowCameraGlobally) {
8563            return UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
8564        } else if (getCameraDisabled(
8565                /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) {
8566            return UserManagerInternal.CAMERA_DISABLED_LOCALLY;
8567        }
8568        return UserManagerInternal.CAMERA_NOT_DISABLED;
8569    }
8570
8571    @Override
8572    public Bundle getUserRestrictions(ComponentName who) {
8573        if (!mHasFeature) {
8574            return null;
8575        }
8576        Preconditions.checkNotNull(who, "ComponentName is null");
8577        synchronized (this) {
8578            final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
8579                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8580            return activeAdmin.userRestrictions;
8581        }
8582    }
8583
8584    @Override
8585    public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
8586            boolean hidden) {
8587        int callingUserId = UserHandle.getCallingUserId();
8588        synchronized (this) {
8589            // Ensure the caller is a DO/PO or a package access delegate.
8590            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8591                    DELEGATION_PACKAGE_ACCESS);
8592
8593            long id = mInjector.binderClearCallingIdentity();
8594            try {
8595                return mIPackageManager.setApplicationHiddenSettingAsUser(
8596                        packageName, hidden, callingUserId);
8597            } catch (RemoteException re) {
8598                // shouldn't happen
8599                Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
8600            } finally {
8601                mInjector.binderRestoreCallingIdentity(id);
8602            }
8603            return false;
8604        }
8605    }
8606
8607    @Override
8608    public boolean isApplicationHidden(ComponentName who, String callerPackage,
8609            String packageName) {
8610        int callingUserId = UserHandle.getCallingUserId();
8611        synchronized (this) {
8612            // Ensure the caller is a DO/PO or a package access delegate.
8613            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8614                    DELEGATION_PACKAGE_ACCESS);
8615
8616            long id = mInjector.binderClearCallingIdentity();
8617            try {
8618                return mIPackageManager.getApplicationHiddenSettingAsUser(
8619                        packageName, callingUserId);
8620            } catch (RemoteException re) {
8621                // shouldn't happen
8622                Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
8623            } finally {
8624                mInjector.binderRestoreCallingIdentity(id);
8625            }
8626            return false;
8627        }
8628    }
8629
8630    @Override
8631    public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
8632        synchronized (this) {
8633            // Ensure the caller is a DO/PO or an enable system app delegate.
8634            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8635                    DELEGATION_ENABLE_SYSTEM_APP);
8636
8637            final boolean isDemo = isCurrentUserDemo();
8638
8639            int userId = UserHandle.getCallingUserId();
8640            long id = mInjector.binderClearCallingIdentity();
8641
8642            try {
8643                if (VERBOSE_LOG) {
8644                    Slog.v(LOG_TAG, "installing " + packageName + " for "
8645                            + userId);
8646                }
8647
8648                int parentUserId = getProfileParentId(userId);
8649                if (!isDemo && !isSystemApp(mIPackageManager, packageName, parentUserId)) {
8650                    throw new IllegalArgumentException("Only system apps can be enabled this way.");
8651                }
8652
8653                // Install the app.
8654                mIPackageManager.installExistingPackageAsUser(packageName, userId,
8655                        0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8656                if (isDemo) {
8657                    // Ensure the app is also ENABLED for demo users.
8658                    mIPackageManager.setApplicationEnabledSetting(packageName,
8659                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
8660                            PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
8661                }
8662            } catch (RemoteException re) {
8663                // shouldn't happen
8664                Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
8665            } finally {
8666                mInjector.binderRestoreCallingIdentity(id);
8667            }
8668        }
8669    }
8670
8671    @Override
8672    public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
8673        synchronized (this) {
8674            // Ensure the caller is a DO/PO or an enable system app delegate.
8675            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8676                    DELEGATION_ENABLE_SYSTEM_APP);
8677
8678            int userId = UserHandle.getCallingUserId();
8679            long id = mInjector.binderClearCallingIdentity();
8680
8681            try {
8682                int parentUserId = getProfileParentId(userId);
8683                List<ResolveInfo> activitiesToEnable = mIPackageManager
8684                        .queryIntentActivities(intent,
8685                                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
8686                                PackageManager.MATCH_DIRECT_BOOT_AWARE
8687                                        | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
8688                                parentUserId)
8689                        .getList();
8690
8691                if (VERBOSE_LOG) {
8692                    Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
8693                }
8694                int numberOfAppsInstalled = 0;
8695                if (activitiesToEnable != null) {
8696                    for (ResolveInfo info : activitiesToEnable) {
8697                        if (info.activityInfo != null) {
8698                            String packageName = info.activityInfo.packageName;
8699                            if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
8700                                numberOfAppsInstalled++;
8701                                mIPackageManager.installExistingPackageAsUser(packageName, userId,
8702                                        0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8703                            } else {
8704                                Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
8705                                        + " system app");
8706                            }
8707                        }
8708                    }
8709                }
8710                return numberOfAppsInstalled;
8711            } catch (RemoteException e) {
8712                // shouldn't happen
8713                Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
8714                return 0;
8715            } finally {
8716                mInjector.binderRestoreCallingIdentity(id);
8717            }
8718        }
8719    }
8720
8721    private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
8722            throws RemoteException {
8723        ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
8724                userId);
8725        if (appInfo == null) {
8726            throw new IllegalArgumentException("The application " + packageName +
8727                    " is not present on this device");
8728        }
8729        return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
8730    }
8731
8732    @Override
8733    public boolean installExistingPackage(ComponentName who, String callerPackage,
8734            String packageName) {
8735        synchronized (this) {
8736            // Ensure the caller is a PO or an install existing package delegate
8737            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8738                    DELEGATION_INSTALL_EXISTING_PACKAGE);
8739            final int callingUserId = mInjector.userHandleGetCallingUserId();
8740            if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
8741                throw new SecurityException("Admin " + who +
8742                        " is neither the device owner or affiliated user's profile owner.");
8743            }
8744
8745            final long id = mInjector.binderClearCallingIdentity();
8746            try {
8747                if (VERBOSE_LOG) {
8748                    Slog.v(LOG_TAG, "installing " + packageName + " for "
8749                            + callingUserId);
8750                }
8751
8752                // Install the package.
8753                return mIPackageManager.installExistingPackageAsUser(packageName, callingUserId,
8754                        0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY)
8755                        == PackageManager.INSTALL_SUCCEEDED;
8756            } catch (RemoteException re) {
8757                // shouldn't happen
8758                return false;
8759            } finally {
8760                mInjector.binderRestoreCallingIdentity(id);
8761            }
8762        }
8763    }
8764
8765    @Override
8766    public void setAccountManagementDisabled(ComponentName who, String accountType,
8767            boolean disabled) {
8768        if (!mHasFeature) {
8769            return;
8770        }
8771        Preconditions.checkNotNull(who, "ComponentName is null");
8772        synchronized (this) {
8773            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
8774                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8775            if (disabled) {
8776                ap.accountTypesWithManagementDisabled.add(accountType);
8777            } else {
8778                ap.accountTypesWithManagementDisabled.remove(accountType);
8779            }
8780            saveSettingsLocked(UserHandle.getCallingUserId());
8781        }
8782    }
8783
8784    @Override
8785    public String[] getAccountTypesWithManagementDisabled() {
8786        return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
8787    }
8788
8789    @Override
8790    public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
8791        enforceFullCrossUsersPermission(userId);
8792        if (!mHasFeature) {
8793            return null;
8794        }
8795        synchronized (this) {
8796            DevicePolicyData policy = getUserData(userId);
8797            final int N = policy.mAdminList.size();
8798            ArraySet<String> resultSet = new ArraySet<>();
8799            for (int i = 0; i < N; i++) {
8800                ActiveAdmin admin = policy.mAdminList.get(i);
8801                resultSet.addAll(admin.accountTypesWithManagementDisabled);
8802            }
8803            return resultSet.toArray(new String[resultSet.size()]);
8804        }
8805    }
8806
8807    @Override
8808    public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
8809            boolean uninstallBlocked) {
8810        final int userId = UserHandle.getCallingUserId();
8811        synchronized (this) {
8812            // Ensure the caller is a DO/PO or a block uninstall delegate
8813            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8814                    DELEGATION_BLOCK_UNINSTALL);
8815
8816            long id = mInjector.binderClearCallingIdentity();
8817            try {
8818                mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
8819            } catch (RemoteException re) {
8820                // Shouldn't happen.
8821                Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
8822            } finally {
8823                mInjector.binderRestoreCallingIdentity(id);
8824            }
8825        }
8826    }
8827
8828    @Override
8829    public boolean isUninstallBlocked(ComponentName who, String packageName) {
8830        // This function should return true if and only if the package is blocked by
8831        // setUninstallBlocked(). It should still return false for other cases of blocks, such as
8832        // when the package is a system app, or when it is an active device admin.
8833        final int userId = UserHandle.getCallingUserId();
8834
8835        synchronized (this) {
8836            if (who != null) {
8837                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8838            }
8839
8840            long id = mInjector.binderClearCallingIdentity();
8841            try {
8842                return mIPackageManager.getBlockUninstallForUser(packageName, userId);
8843            } catch (RemoteException re) {
8844                // Shouldn't happen.
8845                Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
8846            } finally {
8847                mInjector.binderRestoreCallingIdentity(id);
8848            }
8849        }
8850        return false;
8851    }
8852
8853    @Override
8854    public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
8855        if (!mHasFeature) {
8856            return;
8857        }
8858        Preconditions.checkNotNull(who, "ComponentName is null");
8859        synchronized (this) {
8860            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8861                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8862            if (admin.disableCallerId != disabled) {
8863                admin.disableCallerId = disabled;
8864                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
8865            }
8866        }
8867    }
8868
8869    @Override
8870    public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
8871        if (!mHasFeature) {
8872            return false;
8873        }
8874        Preconditions.checkNotNull(who, "ComponentName is null");
8875        synchronized (this) {
8876            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8877                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8878            return admin.disableCallerId;
8879        }
8880    }
8881
8882    @Override
8883    public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
8884        enforceCrossUsersPermission(userId);
8885        synchronized (this) {
8886            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8887            return (admin != null) ? admin.disableCallerId : false;
8888        }
8889    }
8890
8891    @Override
8892    public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
8893        if (!mHasFeature) {
8894            return;
8895        }
8896        Preconditions.checkNotNull(who, "ComponentName is null");
8897        synchronized (this) {
8898            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8899                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8900            if (admin.disableContactsSearch != disabled) {
8901                admin.disableContactsSearch = disabled;
8902                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
8903            }
8904        }
8905    }
8906
8907    @Override
8908    public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
8909        if (!mHasFeature) {
8910            return false;
8911        }
8912        Preconditions.checkNotNull(who, "ComponentName is null");
8913        synchronized (this) {
8914            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8915                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8916            return admin.disableContactsSearch;
8917        }
8918    }
8919
8920    @Override
8921    public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
8922        enforceCrossUsersPermission(userId);
8923        synchronized (this) {
8924            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8925            return (admin != null) ? admin.disableContactsSearch : false;
8926        }
8927    }
8928
8929    @Override
8930    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
8931            boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
8932        final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
8933                actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
8934        final int callingUserId = UserHandle.getCallingUserId();
8935
8936        final long ident = mInjector.binderClearCallingIdentity();
8937        try {
8938            synchronized (this) {
8939                final int managedUserId = getManagedUserId(callingUserId);
8940                if (managedUserId < 0) {
8941                    return;
8942                }
8943                if (isCrossProfileQuickContactDisabled(managedUserId)) {
8944                    if (VERBOSE_LOG) {
8945                        Log.v(LOG_TAG,
8946                                "Cross-profile contacts access disabled for user " + managedUserId);
8947                    }
8948                    return;
8949                }
8950                ContactsInternal.startQuickContactWithErrorToastForUser(
8951                        mContext, intent, new UserHandle(managedUserId));
8952            }
8953        } finally {
8954            mInjector.binderRestoreCallingIdentity(ident);
8955        }
8956    }
8957
8958    /**
8959     * @return true if cross-profile QuickContact is disabled
8960     */
8961    private boolean isCrossProfileQuickContactDisabled(int userId) {
8962        return getCrossProfileCallerIdDisabledForUser(userId)
8963                && getCrossProfileContactsSearchDisabledForUser(userId);
8964    }
8965
8966    /**
8967     * @return the user ID of the managed user that is linked to the current user, if any.
8968     * Otherwise -1.
8969     */
8970    public int getManagedUserId(int callingUserId) {
8971        if (VERBOSE_LOG) {
8972            Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
8973        }
8974
8975        for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
8976            if (ui.id == callingUserId || !ui.isManagedProfile()) {
8977                continue; // Caller user self, or not a managed profile.  Skip.
8978            }
8979            if (VERBOSE_LOG) {
8980                Log.v(LOG_TAG, "Managed user=" + ui.id);
8981            }
8982            return ui.id;
8983        }
8984        if (VERBOSE_LOG) {
8985            Log.v(LOG_TAG, "Managed user not found.");
8986        }
8987        return -1;
8988    }
8989
8990    @Override
8991    public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
8992        if (!mHasFeature) {
8993            return;
8994        }
8995        Preconditions.checkNotNull(who, "ComponentName is null");
8996        synchronized (this) {
8997            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8998                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8999            if (admin.disableBluetoothContactSharing != disabled) {
9000                admin.disableBluetoothContactSharing = disabled;
9001                saveSettingsLocked(UserHandle.getCallingUserId());
9002            }
9003        }
9004    }
9005
9006    @Override
9007    public boolean getBluetoothContactSharingDisabled(ComponentName who) {
9008        if (!mHasFeature) {
9009            return false;
9010        }
9011        Preconditions.checkNotNull(who, "ComponentName is null");
9012        synchronized (this) {
9013            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9014                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9015            return admin.disableBluetoothContactSharing;
9016        }
9017    }
9018
9019    @Override
9020    public boolean getBluetoothContactSharingDisabledForUser(int userId) {
9021        // TODO: Should there be a check to make sure this relationship is
9022        // within a profile group?
9023        // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
9024        synchronized (this) {
9025            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9026            return (admin != null) ? admin.disableBluetoothContactSharing : false;
9027        }
9028    }
9029
9030    @Override
9031    public void setLockTaskPackages(ComponentName who, String[] packages)
9032            throws SecurityException {
9033        Preconditions.checkNotNull(who, "ComponentName is null");
9034        Preconditions.checkNotNull(packages, "packages is null");
9035
9036        synchronized (this) {
9037            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9038            final int userHandle = mInjector.userHandleGetCallingUserId();
9039            if (isUserAffiliatedWithDeviceLocked(userHandle)) {
9040                setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
9041            } else {
9042                throw new SecurityException("Admin " + who +
9043                    " is neither the device owner or affiliated user's profile owner.");
9044            }
9045        }
9046    }
9047
9048    private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
9049        DevicePolicyData policy = getUserData(userHandle);
9050        policy.mLockTaskPackages = packages;
9051
9052        // Store the settings persistently.
9053        saveSettingsLocked(userHandle);
9054        updateLockTaskPackagesLocked(packages, userHandle);
9055    }
9056
9057    @Override
9058    public String[] getLockTaskPackages(ComponentName who) {
9059        Preconditions.checkNotNull(who, "ComponentName is null");
9060
9061        final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
9062        synchronized (this) {
9063            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9064            if (!isUserAffiliatedWithDeviceLocked(userHandle)) {
9065                throw new SecurityException("Admin " + who +
9066                    " is neither the device owner or affiliated user's profile owner.");
9067            }
9068
9069            final List<String> packages = getUserData(userHandle).mLockTaskPackages;
9070            return packages.toArray(new String[packages.size()]);
9071        }
9072    }
9073
9074    @Override
9075    public boolean isLockTaskPermitted(String pkg) {
9076        final int userHandle = mInjector.userHandleGetCallingUserId();
9077        synchronized (this) {
9078            return getUserData(userHandle).mLockTaskPackages.contains(pkg);
9079        }
9080    }
9081
9082    @Override
9083    public void setLockTaskFeatures(ComponentName who, int flags) {
9084        Preconditions.checkNotNull(who, "ComponentName is null");
9085        final int userHandle = mInjector.userHandleGetCallingUserId();
9086        synchronized (this) {
9087            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9088            if (!isUserAffiliatedWithDeviceLocked(userHandle)) {
9089                throw new SecurityException("Admin " + who +
9090                        " is neither the device owner or affiliated user's profile owner.");
9091            }
9092            setLockTaskFeaturesLocked(userHandle, flags);
9093        }
9094    }
9095
9096    private void setLockTaskFeaturesLocked(int userHandle, int flags) {
9097        DevicePolicyData policy = getUserData(userHandle);
9098        policy.mLockTaskFeatures = flags;
9099        saveSettingsLocked(userHandle);
9100        updateLockTaskFeaturesLocked(flags, userHandle);
9101    }
9102
9103    @Override
9104    public int getLockTaskFeatures(ComponentName who) {
9105        Preconditions.checkNotNull(who, "ComponentName is null");
9106        final int userHandle = mInjector.userHandleGetCallingUserId();
9107        synchronized (this) {
9108            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9109            if (!isUserAffiliatedWithDeviceLocked(userHandle)) {
9110                throw new SecurityException("Admin " + who +
9111                        " is neither the device owner or affiliated user's profile owner.");
9112            }
9113            return getUserData(userHandle).mLockTaskFeatures;
9114        }
9115    }
9116
9117    private void maybeClearLockTaskPolicyLocked() {
9118        final long ident = mInjector.binderClearCallingIdentity();
9119        try {
9120            final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
9121            for (int i = userInfos.size() - 1; i >= 0; i--) {
9122                int userId = userInfos.get(i).id;
9123                if (isUserAffiliatedWithDeviceLocked(userId)) {
9124                    continue;
9125                }
9126
9127                final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
9128                if (!lockTaskPackages.isEmpty()) {
9129                    Slog.d(LOG_TAG,
9130                            "User id " + userId + " not affiliated. Clearing lock task packages");
9131                    setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
9132                }
9133                final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures;
9134                if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){
9135                    Slog.d(LOG_TAG,
9136                            "User id " + userId + " not affiliated. Clearing lock task features");
9137                    setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
9138                }
9139            }
9140        } finally {
9141            mInjector.binderRestoreCallingIdentity(ident);
9142        }
9143    }
9144
9145    @Override
9146    public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
9147        if (!isCallerWithSystemUid()) {
9148            throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
9149        }
9150        synchronized (this) {
9151            final DevicePolicyData policy = getUserData(userHandle);
9152
9153            if (policy.mStatusBarDisabled) {
9154                // Status bar is managed by LockTaskController during LockTask, so we cancel this
9155                // policy when LockTask starts, and reapply it when LockTask ends
9156                setStatusBarDisabledInternal(!isEnabled, userHandle);
9157            }
9158
9159            Bundle adminExtras = new Bundle();
9160            adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
9161            for (ActiveAdmin admin : policy.mAdminList) {
9162                final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
9163                final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
9164                if (ownsDevice || ownsProfile) {
9165                    if (isEnabled) {
9166                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
9167                                adminExtras, null);
9168                    } else {
9169                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
9170                    }
9171                }
9172            }
9173        }
9174    }
9175
9176    @Override
9177    public void setGlobalSetting(ComponentName who, String setting, String value) {
9178        Preconditions.checkNotNull(who, "ComponentName is null");
9179
9180        synchronized (this) {
9181            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9182
9183            // Some settings are no supported any more. However we do not want to throw a
9184            // SecurityException to avoid breaking apps.
9185            if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
9186                Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
9187                return;
9188            }
9189
9190            if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)
9191                    && !UserManager.isDeviceInDemoMode(mContext)) {
9192                throw new SecurityException(String.format(
9193                        "Permission denial: device owners cannot update %1$s", setting));
9194            }
9195
9196            if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
9197                // ignore if it contradicts an existing policy
9198                long timeMs = getMaximumTimeToLock(
9199                        who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
9200                if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
9201                    return;
9202                }
9203            }
9204
9205            long id = mInjector.binderClearCallingIdentity();
9206            try {
9207                mInjector.settingsGlobalPutString(setting, value);
9208            } finally {
9209                mInjector.binderRestoreCallingIdentity(id);
9210            }
9211        }
9212    }
9213
9214    @Override
9215    public void setSystemSetting(ComponentName who, String setting, String value) {
9216        Preconditions.checkNotNull(who, "ComponentName is null");
9217        Preconditions.checkStringNotEmpty(setting, "String setting is null or empty");
9218
9219        synchronized (this) {
9220            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9221
9222            if (!SYSTEM_SETTINGS_WHITELIST.contains(setting)) {
9223                throw new SecurityException(String.format(
9224                        "Permission denial: device owners cannot update %1$s", setting));
9225            }
9226
9227            mInjector.binderWithCleanCallingIdentity(() -> mInjector.settingsSystemPutString(
9228                    setting, value));
9229        }
9230    }
9231
9232    @Override
9233    public boolean setTime(ComponentName who, long millis) {
9234        Preconditions.checkNotNull(who, "ComponentName is null in setTime");
9235        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9236        // Don't allow set time when auto time is on.
9237        if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) {
9238            return false;
9239        }
9240        mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis));
9241        return true;
9242    }
9243
9244    @Override
9245    public boolean setTimeZone(ComponentName who, String timeZone) {
9246        Preconditions.checkNotNull(who, "ComponentName is null in setTimeZone");
9247        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9248        // Don't allow set timezone when auto timezone is on.
9249        if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) {
9250            return false;
9251        }
9252        mInjector.binderWithCleanCallingIdentity(() ->
9253            mInjector.getAlarmManager().setTimeZone(timeZone));
9254        return true;
9255    }
9256
9257    @Override
9258    public void setSecureSetting(ComponentName who, String setting, String value) {
9259        Preconditions.checkNotNull(who, "ComponentName is null");
9260        int callingUserId = mInjector.userHandleGetCallingUserId();
9261
9262        synchronized (this) {
9263            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9264
9265            if (isDeviceOwner(who, callingUserId)) {
9266                if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)
9267                        && !isCurrentUserDemo()) {
9268                    throw new SecurityException(String.format(
9269                            "Permission denial: Device owners cannot update %1$s", setting));
9270                }
9271            } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) {
9272                throw new SecurityException(String.format(
9273                        "Permission denial: Profile owners cannot update %1$s", setting));
9274            }
9275            if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
9276                if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
9277                    throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
9278                            + " is deprecated. Please use the user restriction "
9279                            + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " instead.");
9280                }
9281                if (!mUserManager.isManagedProfile(callingUserId)) {
9282                    Slog.e(LOG_TAG, "Ignoring setSecureSetting request for "
9283                            + setting + ". User restriction "
9284                            + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES
9285                            + " should be used instead.");
9286                } else {
9287                    try {
9288                        setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
9289                                (Integer.parseInt(value) == 0) ? true : false);
9290                    } catch (NumberFormatException exc) {
9291                        Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
9292                    }
9293                }
9294                return;
9295            }
9296            long id = mInjector.binderClearCallingIdentity();
9297            try {
9298                if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
9299                    final String currentValue = mInjector.settingsSecureGetStringForUser(
9300                            Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
9301                    if (!TextUtils.equals(currentValue, value)) {
9302                        // Tell the content observer that the next change will be due to the owner
9303                        // changing the value. There is a small race condition here that we cannot
9304                        // avoid: Change notifications are sent asynchronously, so it is possible
9305                        // that there are prior notifications queued up before the one we are about
9306                        // to trigger. This is a corner case that will have no impact in practice.
9307                        mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
9308                    }
9309                    getUserData(callingUserId).mCurrentInputMethodSet = true;
9310                    saveSettingsLocked(callingUserId);
9311                }
9312                mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
9313            } finally {
9314                mInjector.binderRestoreCallingIdentity(id);
9315            }
9316        }
9317    }
9318
9319    @Override
9320    public void setMasterVolumeMuted(ComponentName who, boolean on) {
9321        Preconditions.checkNotNull(who, "ComponentName is null");
9322        synchronized (this) {
9323            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9324            setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on);
9325        }
9326    }
9327
9328    @Override
9329    public boolean isMasterVolumeMuted(ComponentName who) {
9330        Preconditions.checkNotNull(who, "ComponentName is null");
9331        synchronized (this) {
9332            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9333
9334            AudioManager audioManager =
9335                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
9336            return audioManager.isMasterMute();
9337        }
9338    }
9339
9340    @Override
9341    public void setUserIcon(ComponentName who, Bitmap icon) {
9342        synchronized (this) {
9343            Preconditions.checkNotNull(who, "ComponentName is null");
9344            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9345
9346            int userId = UserHandle.getCallingUserId();
9347            long id = mInjector.binderClearCallingIdentity();
9348            try {
9349                mUserManagerInternal.setUserIcon(userId, icon);
9350            } finally {
9351                mInjector.binderRestoreCallingIdentity(id);
9352            }
9353        }
9354    }
9355
9356    @Override
9357    public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
9358        Preconditions.checkNotNull(who, "ComponentName is null");
9359        final int userId = mInjector.userHandleGetCallingUserId();
9360        synchronized (this) {
9361            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9362            if (!isUserAffiliatedWithDeviceLocked(userId)) {
9363                throw new SecurityException("Admin " + who +
9364                        " is neither the device owner or affiliated user's profile owner.");
9365            }
9366        }
9367
9368        long ident = mInjector.binderClearCallingIdentity();
9369        try {
9370            // disallow disabling the keyguard if a password is currently set
9371            if (disabled && mLockPatternUtils.isSecure(userId)) {
9372                return false;
9373            }
9374            mLockPatternUtils.setLockScreenDisabled(disabled, userId);
9375            mInjector.getIWindowManager().dismissKeyguard(null);
9376        } catch (RemoteException e) {
9377            // Same process, does not happen.
9378        } finally {
9379            mInjector.binderRestoreCallingIdentity(ident);
9380        }
9381        return true;
9382    }
9383
9384    @Override
9385    public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
9386        int userId = UserHandle.getCallingUserId();
9387        synchronized (this) {
9388            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9389            if (!isUserAffiliatedWithDeviceLocked(userId)) {
9390                throw new SecurityException("Admin " + who +
9391                        " is neither the device owner or affiliated user's profile owner.");
9392            }
9393            DevicePolicyData policy = getUserData(userId);
9394            if (policy.mStatusBarDisabled != disabled) {
9395                boolean isLockTaskMode = false;
9396                try {
9397                    isLockTaskMode = mInjector.getIActivityManager().getLockTaskModeState()
9398                            != LOCK_TASK_MODE_NONE;
9399                } catch (RemoteException e) {
9400                    Slog.e(LOG_TAG, "Failed to get LockTask mode");
9401                }
9402                if (!isLockTaskMode) {
9403                    if (!setStatusBarDisabledInternal(disabled, userId)) {
9404                        return false;
9405                    }
9406                }
9407                policy.mStatusBarDisabled = disabled;
9408                saveSettingsLocked(userId);
9409            }
9410        }
9411        return true;
9412    }
9413
9414    private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
9415        long ident = mInjector.binderClearCallingIdentity();
9416        try {
9417            IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
9418                    ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
9419            if (statusBarService != null) {
9420                int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
9421                int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
9422                statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
9423                statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
9424                return true;
9425            }
9426        } catch (RemoteException e) {
9427            Slog.e(LOG_TAG, "Failed to disable the status bar", e);
9428        } finally {
9429            mInjector.binderRestoreCallingIdentity(ident);
9430        }
9431        return false;
9432    }
9433
9434    /**
9435     * We need to update the internal state of whether a user has completed setup or a
9436     * device has paired once. After that, we ignore any changes that reset the
9437     * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
9438     * as we don't trust any apps that might try to reset them.
9439     * <p>
9440     * Unfortunately, we don't know which user's setup state was changed, so we write all of
9441     * them.
9442     */
9443    void updateUserSetupCompleteAndPaired() {
9444        List<UserInfo> users = mUserManager.getUsers(true);
9445        final int N = users.size();
9446        for (int i = 0; i < N; i++) {
9447            int userHandle = users.get(i).id;
9448            if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
9449                    userHandle) != 0) {
9450                DevicePolicyData policy = getUserData(userHandle);
9451                if (!policy.mUserSetupComplete) {
9452                    policy.mUserSetupComplete = true;
9453                    synchronized (this) {
9454                        saveSettingsLocked(userHandle);
9455                    }
9456                }
9457            }
9458            if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
9459                    userHandle) != 0) {
9460                DevicePolicyData policy = getUserData(userHandle);
9461                if (!policy.mPaired) {
9462                    policy.mPaired = true;
9463                    synchronized (this) {
9464                        saveSettingsLocked(userHandle);
9465                    }
9466                }
9467            }
9468        }
9469    }
9470
9471    private class SetupContentObserver extends ContentObserver {
9472        private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
9473                Settings.Secure.USER_SETUP_COMPLETE);
9474        private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
9475                Settings.Global.DEVICE_PROVISIONED);
9476        private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
9477        private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
9478                Settings.Secure.DEFAULT_INPUT_METHOD);
9479
9480        @GuardedBy("DevicePolicyManagerService.this")
9481        private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();
9482
9483        public SetupContentObserver(Handler handler) {
9484            super(handler);
9485        }
9486
9487        void register() {
9488            mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
9489            mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
9490            if (mIsWatch) {
9491                mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
9492            }
9493            mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
9494        }
9495
9496        private void addPendingChangeByOwnerLocked(int userId) {
9497            mUserIdsWithPendingChangesByOwner.add(userId);
9498        }
9499
9500        @Override
9501        public void onChange(boolean selfChange, Uri uri, int userId) {
9502            if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
9503                updateUserSetupCompleteAndPaired();
9504            } else if (mDeviceProvisioned.equals(uri)) {
9505                synchronized (DevicePolicyManagerService.this) {
9506                    // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
9507                    // is delayed until device is marked as provisioned.
9508                    setDeviceOwnerSystemPropertyLocked();
9509                }
9510            } else if (mDefaultImeChanged.equals(uri)) {
9511                synchronized (DevicePolicyManagerService.this) {
9512                    if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
9513                        // This change notification was triggered by the owner changing the current
9514                        // IME. Ignore it.
9515                        mUserIdsWithPendingChangesByOwner.remove(userId);
9516                    } else {
9517                        // This change notification was triggered by the user manually changing the
9518                        // current IME.
9519                        getUserData(userId).mCurrentInputMethodSet = false;
9520                        saveSettingsLocked(userId);
9521                    }
9522                }
9523            }
9524        }
9525    }
9526
9527    @VisibleForTesting
9528    final class LocalService extends DevicePolicyManagerInternal {
9529        private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
9530
9531        @Override
9532        public List<String> getCrossProfileWidgetProviders(int profileId) {
9533            synchronized (DevicePolicyManagerService.this) {
9534                if (mOwners == null) {
9535                    return Collections.emptyList();
9536                }
9537                ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
9538                if (ownerComponent == null) {
9539                    return Collections.emptyList();
9540                }
9541
9542                DevicePolicyData policy = getUserDataUnchecked(profileId);
9543                ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
9544
9545                if (admin == null || admin.crossProfileWidgetProviders == null
9546                        || admin.crossProfileWidgetProviders.isEmpty()) {
9547                    return Collections.emptyList();
9548                }
9549
9550                return admin.crossProfileWidgetProviders;
9551            }
9552        }
9553
9554        @Override
9555        public void addOnCrossProfileWidgetProvidersChangeListener(
9556                OnCrossProfileWidgetProvidersChangeListener listener) {
9557            synchronized (DevicePolicyManagerService.this) {
9558                if (mWidgetProviderListeners == null) {
9559                    mWidgetProviderListeners = new ArrayList<>();
9560                }
9561                if (!mWidgetProviderListeners.contains(listener)) {
9562                    mWidgetProviderListeners.add(listener);
9563                }
9564            }
9565        }
9566
9567        @Override
9568        public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
9569            synchronized(DevicePolicyManagerService.this) {
9570                return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
9571            }
9572        }
9573
9574        private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
9575            final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
9576            synchronized (DevicePolicyManagerService.this) {
9577                listeners = new ArrayList<>(mWidgetProviderListeners);
9578            }
9579            final int listenerCount = listeners.size();
9580            for (int i = 0; i < listenerCount; i++) {
9581                OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
9582                listener.onCrossProfileWidgetProvidersChanged(userId, packages);
9583            }
9584        }
9585
9586        @Override
9587        public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
9588            // This method is called from AM with its lock held, so don't take the DPMS lock.
9589            // b/29242568
9590
9591            ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
9592            if (profileOwner != null) {
9593                return DevicePolicyManagerService.this
9594                        .createShowAdminSupportIntent(profileOwner, userId);
9595            }
9596
9597            final Pair<Integer, ComponentName> deviceOwner =
9598                    mOwners.getDeviceOwnerUserIdAndComponent();
9599            if (deviceOwner != null && deviceOwner.first == userId) {
9600                return DevicePolicyManagerService.this
9601                        .createShowAdminSupportIntent(deviceOwner.second, userId);
9602            }
9603
9604            // We're not specifying the device admin because there isn't one.
9605            if (useDefaultIfNoAdmin) {
9606                return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
9607            }
9608            return null;
9609        }
9610
9611        @Override
9612        public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
9613            int source;
9614            long ident = mInjector.binderClearCallingIdentity();
9615            try {
9616                source = mUserManager.getUserRestrictionSource(userRestriction,
9617                        UserHandle.of(userId));
9618            } finally {
9619                mInjector.binderRestoreCallingIdentity(ident);
9620            }
9621            if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) {
9622                /*
9623                 * In this case, the user restriction is enforced by the system.
9624                 * So we won't show an admin support intent, even if it is also
9625                 * enforced by a profile/device owner.
9626                 */
9627                return null;
9628            }
9629            boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0;
9630            boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0;
9631            if (enforcedByDo && enforcedByPo) {
9632                // In this case, we'll show an admin support dialog that does not
9633                // specify the admin.
9634                return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
9635            } else if (enforcedByPo) {
9636                final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
9637                if (profileOwner != null) {
9638                    return DevicePolicyManagerService.this
9639                            .createShowAdminSupportIntent(profileOwner, userId);
9640                }
9641                // This could happen if another thread has changed the profile owner since we called
9642                // getUserRestrictionSource
9643                return null;
9644            } else if (enforcedByDo) {
9645                final Pair<Integer, ComponentName> deviceOwner
9646                        = mOwners.getDeviceOwnerUserIdAndComponent();
9647                if (deviceOwner != null) {
9648                    return DevicePolicyManagerService.this
9649                            .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first);
9650                }
9651                // This could happen if another thread has changed the device owner since we called
9652                // getUserRestrictionSource
9653                return null;
9654            }
9655            return null;
9656        }
9657
9658        @Override
9659        public boolean isUserAffiliatedWithDevice(int userId) {
9660            return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId);
9661        }
9662    }
9663
9664    private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
9665        // This method is called with AMS lock held, so don't take DPMS lock
9666        final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
9667        intent.putExtra(Intent.EXTRA_USER_ID, userId);
9668        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
9669        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9670        return intent;
9671    }
9672
9673    @Override
9674    public Intent createAdminSupportIntent(String restriction) {
9675        Preconditions.checkNotNull(restriction);
9676        final int uid = mInjector.binderGetCallingUid();
9677        final int userId = UserHandle.getUserId(uid);
9678        Intent intent = null;
9679        if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) ||
9680                DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
9681            synchronized(this) {
9682                final DevicePolicyData policy = getUserData(userId);
9683                final int N = policy.mAdminList.size();
9684                for (int i = 0; i < N; i++) {
9685                    final ActiveAdmin admin = policy.mAdminList.get(i);
9686                    if ((admin.disableCamera &&
9687                                DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) ||
9688                        (admin.disableScreenCapture && DevicePolicyManager
9689                                .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) {
9690                        intent = createShowAdminSupportIntent(admin.info.getComponent(), userId);
9691                        break;
9692                    }
9693                }
9694                // For the camera, a device owner on a different user can disable it globally,
9695                // so we need an additional check.
9696                if (intent == null
9697                        && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
9698                    final ActiveAdmin admin = getDeviceOwnerAdminLocked();
9699                    if (admin != null && admin.disableCamera) {
9700                        intent = createShowAdminSupportIntent(admin.info.getComponent(),
9701                                mOwners.getDeviceOwnerUserId());
9702                    }
9703                }
9704            }
9705        } else {
9706            // if valid, |restriction| can only be a user restriction
9707            intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction);
9708        }
9709        if (intent != null) {
9710            intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
9711        }
9712        return intent;
9713    }
9714
9715    /**
9716     * Returns true if specified admin is allowed to limit passwords and has a
9717     * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
9718     */
9719    private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
9720        if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
9721            return false;
9722        }
9723        return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
9724    }
9725
9726    @Override
9727    public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
9728        if (policy != null && !policy.isValid()) {
9729            throw new IllegalArgumentException("Invalid system update policy.");
9730        }
9731        synchronized (this) {
9732            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9733            if (policy == null) {
9734                mOwners.clearSystemUpdatePolicy();
9735            } else {
9736                mOwners.setSystemUpdatePolicy(policy);
9737            }
9738            mOwners.writeDeviceOwner();
9739        }
9740        mContext.sendBroadcastAsUser(
9741                new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
9742                UserHandle.SYSTEM);
9743    }
9744
9745    @Override
9746    public SystemUpdatePolicy getSystemUpdatePolicy() {
9747        synchronized (this) {
9748            SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
9749            if (policy != null && !policy.isValid()) {
9750                Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
9751                return null;
9752            }
9753            return policy;
9754        }
9755    }
9756
9757    /**
9758     * Checks if the caller of the method is the device owner app.
9759     *
9760     * @param callerUid UID of the caller.
9761     * @return true if the caller is the device owner app
9762     */
9763    @VisibleForTesting
9764    boolean isCallerDeviceOwner(int callerUid) {
9765        synchronized (this) {
9766            if (!mOwners.hasDeviceOwner()) {
9767                return false;
9768            }
9769            if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
9770                return false;
9771            }
9772            final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
9773                    .getPackageName();
9774                try {
9775                    String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid);
9776                    for (String pkg : pkgs) {
9777                        if (deviceOwnerPackageName.equals(pkg)) {
9778                            return true;
9779                        }
9780                    }
9781                } catch (RemoteException e) {
9782                    return false;
9783                }
9784        }
9785
9786        return false;
9787    }
9788
9789    @Override
9790    public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
9791        mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
9792                "Only the system update service can broadcast update information");
9793
9794        if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
9795            Slog.w(LOG_TAG, "Only the system update service in the system user " +
9796                    "can broadcast update information.");
9797            return;
9798        }
9799
9800        if (!mOwners.saveSystemUpdateInfo(info)) {
9801            // Pending system update hasn't changed, don't send duplicate notification.
9802            return;
9803        }
9804
9805        final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
9806                .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
9807                        info == null ? -1 : info.getReceivedTime());
9808
9809        final long ident = mInjector.binderClearCallingIdentity();
9810        try {
9811            synchronized (this) {
9812                // Broadcast to device owner first if there is one.
9813                if (mOwners.hasDeviceOwner()) {
9814                    final UserHandle deviceOwnerUser =
9815                            UserHandle.of(mOwners.getDeviceOwnerUserId());
9816                    intent.setComponent(mOwners.getDeviceOwnerComponent());
9817                    mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
9818                }
9819            }
9820            // Get running users.
9821            final int runningUserIds[];
9822            try {
9823                runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
9824            } catch (RemoteException e) {
9825                // Shouldn't happen.
9826                Log.e(LOG_TAG, "Could not retrieve the list of running users", e);
9827                return;
9828            }
9829            // Send broadcasts to corresponding profile owners if any.
9830            for (final int userId : runningUserIds) {
9831                synchronized (this) {
9832                    final ComponentName profileOwnerPackage =
9833                            mOwners.getProfileOwnerComponent(userId);
9834                    if (profileOwnerPackage != null) {
9835                        intent.setComponent(profileOwnerPackage);
9836                        mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
9837                    }
9838                }
9839            }
9840        } finally {
9841            mInjector.binderRestoreCallingIdentity(ident);
9842        }
9843    }
9844
9845    @Override
9846    public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
9847        Preconditions.checkNotNull(admin, "ComponentName is null");
9848        enforceProfileOrDeviceOwner(admin);
9849
9850        return mOwners.getSystemUpdateInfo();
9851    }
9852
9853    @Override
9854    public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy)
9855            throws RemoteException {
9856        int userId = UserHandle.getCallingUserId();
9857        synchronized (this) {
9858            // Ensure the caller is a DO/PO or a permission grant state delegate.
9859            enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9860                    DELEGATION_PERMISSION_GRANT);
9861            DevicePolicyData userPolicy = getUserData(userId);
9862            if (userPolicy.mPermissionPolicy != policy) {
9863                userPolicy.mPermissionPolicy = policy;
9864                saveSettingsLocked(userId);
9865            }
9866        }
9867    }
9868
9869    @Override
9870    public int getPermissionPolicy(ComponentName admin) throws RemoteException {
9871        int userId = UserHandle.getCallingUserId();
9872        synchronized (this) {
9873            DevicePolicyData userPolicy = getUserData(userId);
9874            return userPolicy.mPermissionPolicy;
9875        }
9876    }
9877
9878    @Override
9879    public boolean setPermissionGrantState(ComponentName admin, String callerPackage,
9880            String packageName, String permission, int grantState) throws RemoteException {
9881        UserHandle user = mInjector.binderGetCallingUserHandle();
9882        synchronized (this) {
9883            // Ensure the caller is a DO/PO or a permission grant state delegate.
9884            enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9885                    DELEGATION_PERMISSION_GRANT);
9886            long ident = mInjector.binderClearCallingIdentity();
9887            try {
9888                if (getTargetSdk(packageName, user.getIdentifier())
9889                        < android.os.Build.VERSION_CODES.M) {
9890                    return false;
9891                }
9892                if (!isRuntimePermission(permission)) {
9893                    return false;
9894                }
9895                final PackageManager packageManager = mInjector.getPackageManager();
9896                switch (grantState) {
9897                    case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
9898                        mInjector.getPackageManagerInternal().grantRuntimePermission(packageName,
9899                                permission, user.getIdentifier(), true /* override policy */);
9900                        packageManager.updatePermissionFlags(permission, packageName,
9901                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
9902                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
9903                    } break;
9904
9905                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
9906                        mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName,
9907                                permission, user.getIdentifier(), true /* override policy */);
9908                        packageManager.updatePermissionFlags(permission, packageName,
9909                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
9910                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
9911                    } break;
9912
9913                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
9914                        packageManager.updatePermissionFlags(permission, packageName,
9915                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
9916                    } break;
9917                }
9918                return true;
9919            } catch (SecurityException se) {
9920                return false;
9921            } catch (NameNotFoundException e) {
9922                return false;
9923            } finally {
9924                mInjector.binderRestoreCallingIdentity(ident);
9925            }
9926        }
9927    }
9928
9929    @Override
9930    public int getPermissionGrantState(ComponentName admin, String callerPackage,
9931            String packageName, String permission) throws RemoteException {
9932        PackageManager packageManager = mInjector.getPackageManager();
9933
9934        UserHandle user = mInjector.binderGetCallingUserHandle();
9935        if (!isCallerWithSystemUid()) {
9936            // Ensure the caller is a DO/PO or a permission grant state delegate.
9937            enforceCanManageScope(admin, callerPackage,
9938                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT);
9939        }
9940        synchronized (this) {
9941            long ident = mInjector.binderClearCallingIdentity();
9942            try {
9943                int granted = mIPackageManager.checkPermission(permission,
9944                        packageName, user.getIdentifier());
9945                int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
9946                if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
9947                        != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
9948                    // Not controlled by policy
9949                    return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
9950                } else {
9951                    // Policy controlled so return result based on permission grant state
9952                    return granted == PackageManager.PERMISSION_GRANTED
9953                            ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
9954                            : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
9955                }
9956            } finally {
9957                mInjector.binderRestoreCallingIdentity(ident);
9958            }
9959        }
9960    }
9961
9962    boolean isPackageInstalledForUser(String packageName, int userHandle) {
9963        try {
9964            PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
9965                    userHandle);
9966            return (pi != null) && (pi.applicationInfo.flags != 0);
9967        } catch (RemoteException re) {
9968            throw new RuntimeException("Package manager has died", re);
9969        }
9970    }
9971
9972    public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
9973        final PackageManager packageManager = mInjector.getPackageManager();
9974        PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
9975        return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
9976                == PermissionInfo.PROTECTION_DANGEROUS;
9977    }
9978
9979    @Override
9980    public boolean isProvisioningAllowed(String action, String packageName) {
9981        Preconditions.checkNotNull(packageName);
9982
9983        final int callingUid = mInjector.binderGetCallingUid();
9984        final long ident = mInjector.binderClearCallingIdentity();
9985        try {
9986            final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser(
9987                    packageName, UserHandle.getUserId(callingUid));
9988            Preconditions.checkArgument(callingUid == uidForPackage,
9989                    "Caller uid doesn't match the one for the provided package.");
9990        } catch (NameNotFoundException e) {
9991            throw new IllegalArgumentException("Invalid package provided " + packageName, e);
9992        } finally {
9993            mInjector.binderRestoreCallingIdentity(ident);
9994        }
9995
9996        return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK;
9997    }
9998
9999    @Override
10000    public int checkProvisioningPreCondition(String action, String packageName) {
10001        Preconditions.checkNotNull(packageName);
10002        enforceCanManageProfileAndDeviceOwners();
10003        return checkProvisioningPreConditionSkipPermission(action, packageName);
10004    }
10005
10006    private int checkProvisioningPreConditionSkipPermission(String action, String packageName) {
10007        if (!mHasFeature) {
10008            return CODE_DEVICE_ADMIN_NOT_SUPPORTED;
10009        }
10010
10011        final int callingUserId = mInjector.userHandleGetCallingUserId();
10012        if (action != null) {
10013            switch (action) {
10014                case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
10015                    return checkManagedProfileProvisioningPreCondition(packageName, callingUserId);
10016                case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
10017                    return checkDeviceOwnerProvisioningPreCondition(callingUserId);
10018                case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER:
10019                    return checkManagedUserProvisioningPreCondition(callingUserId);
10020                case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE:
10021                    return checkManagedShareableDeviceProvisioningPreCondition(callingUserId);
10022            }
10023        }
10024        throw new IllegalArgumentException("Unknown provisioning action " + action);
10025    }
10026
10027    /**
10028     * The device owner can only be set before the setup phase of the primary user has completed,
10029     * except for adb command if no accounts or additional users are present on the device.
10030     */
10031    private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
10032            int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) {
10033        if (mOwners.hasDeviceOwner()) {
10034            return CODE_HAS_DEVICE_OWNER;
10035        }
10036        if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
10037            return CODE_USER_HAS_PROFILE_OWNER;
10038        }
10039        if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
10040            return CODE_USER_NOT_RUNNING;
10041        }
10042        if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
10043            return CODE_HAS_PAIRED;
10044        }
10045        if (isAdb) {
10046            // if shell command runs after user setup completed check device status. Otherwise, OK.
10047            if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
10048                if (!mInjector.userManagerIsSplitSystemUser()) {
10049                    if (mUserManager.getUserCount() > 1) {
10050                        return CODE_NONSYSTEM_USER_EXISTS;
10051                    }
10052                    if (hasIncompatibleAccountsOrNonAdb) {
10053                        return CODE_ACCOUNTS_NOT_EMPTY;
10054                    }
10055                } else {
10056                    // STOPSHIP Do proper check in split user mode
10057                }
10058            }
10059            return CODE_OK;
10060        } else {
10061            if (!mInjector.userManagerIsSplitSystemUser()) {
10062                // In non-split user mode, DO has to be user 0
10063                if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
10064                    return CODE_NOT_SYSTEM_USER;
10065                }
10066                // In non-split user mode, only provision DO before setup wizard completes
10067                if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
10068                    return CODE_USER_SETUP_COMPLETED;
10069                }
10070            } else {
10071                // STOPSHIP Do proper check in split user mode
10072            }
10073            return CODE_OK;
10074        }
10075    }
10076
10077    private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) {
10078        synchronized (this) {
10079            // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
10080            return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
10081                    deviceOwnerUserId, /* isAdb= */ false,
10082                    /* hasIncompatibleAccountsOrNonAdb=*/ true);
10083        }
10084    }
10085
10086    private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) {
10087        if (!hasFeatureManagedUsers()) {
10088            return CODE_MANAGED_USERS_NOT_SUPPORTED;
10089        }
10090        if (callingUserId == UserHandle.USER_SYSTEM
10091                && mInjector.userManagerIsSplitSystemUser()) {
10092            // Managed-profiles cannot be setup on the system user.
10093            return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
10094        }
10095        if (getProfileOwner(callingUserId) != null) {
10096            // Managed user cannot have a managed profile.
10097            return CODE_USER_HAS_PROFILE_OWNER;
10098        }
10099
10100        final long ident = mInjector.binderClearCallingIdentity();
10101        try {
10102            final UserHandle callingUserHandle = UserHandle.of(callingUserId);
10103            final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId);
10104            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
10105                    callingUserHandle)) {
10106                // An admin can initiate provisioning if it has set the restriction.
10107                if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
10108                        UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) {
10109                    return CODE_ADD_MANAGED_PROFILE_DISALLOWED;
10110                }
10111            }
10112            boolean canRemoveProfile = true;
10113            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
10114                    callingUserHandle)) {
10115                // We can remove a profile if the admin itself has set the restriction.
10116                if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
10117                        UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
10118                        callingUserId)) {
10119                    canRemoveProfile = false;
10120                }
10121            }
10122            if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) {
10123                return CODE_CANNOT_ADD_MANAGED_PROFILE;
10124            }
10125        } finally {
10126            mInjector.binderRestoreCallingIdentity(ident);
10127        }
10128        return CODE_OK;
10129    }
10130
10131    private ComponentName getOwnerComponent(String packageName, int userId) {
10132        if (isDeviceOwnerPackage(packageName, userId)) {
10133            return mOwners.getDeviceOwnerComponent();
10134        }
10135        if (isProfileOwnerPackage(packageName, userId)) {
10136            return mOwners.getProfileOwnerComponent(userId);
10137        }
10138        return null;
10139    }
10140
10141    /**
10142     * Return device owner or profile owner set on a given user.
10143     */
10144    private @Nullable ComponentName getOwnerComponent(int userId) {
10145        synchronized (this) {
10146            if (mOwners.getDeviceOwnerUserId() == userId) {
10147                return mOwners.getDeviceOwnerComponent();
10148            }
10149            if (mOwners.hasProfileOwner(userId)) {
10150                return mOwners.getProfileOwnerComponent(userId);
10151            }
10152        }
10153        return null;
10154    }
10155
10156    private int checkManagedUserProvisioningPreCondition(int callingUserId) {
10157        if (!hasFeatureManagedUsers()) {
10158            return CODE_MANAGED_USERS_NOT_SUPPORTED;
10159        }
10160        if (!mInjector.userManagerIsSplitSystemUser()) {
10161            // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
10162            return CODE_NOT_SYSTEM_USER_SPLIT;
10163        }
10164        if (callingUserId == UserHandle.USER_SYSTEM) {
10165            // System user cannot be a managed user.
10166            return CODE_SYSTEM_USER;
10167        }
10168        if (hasUserSetupCompleted(callingUserId)) {
10169            return CODE_USER_SETUP_COMPLETED;
10170        }
10171        if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
10172            return CODE_HAS_PAIRED;
10173        }
10174        return CODE_OK;
10175    }
10176
10177    private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) {
10178        if (!mInjector.userManagerIsSplitSystemUser()) {
10179            // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
10180            return CODE_NOT_SYSTEM_USER_SPLIT;
10181        }
10182        return checkDeviceOwnerProvisioningPreCondition(callingUserId);
10183    }
10184
10185    private boolean hasFeatureManagedUsers() {
10186        try {
10187            return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
10188        } catch (RemoteException e) {
10189            return false;
10190        }
10191    }
10192
10193    @Override
10194    public String getWifiMacAddress(ComponentName admin) {
10195        // Make sure caller has DO.
10196        synchronized (this) {
10197            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10198        }
10199
10200        final long ident = mInjector.binderClearCallingIdentity();
10201        try {
10202            final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
10203            if (wifiInfo == null) {
10204                return null;
10205            }
10206            return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
10207        } finally {
10208            mInjector.binderRestoreCallingIdentity(ident);
10209        }
10210    }
10211
10212    /**
10213     * Returns the target sdk version number that the given packageName was built for
10214     * in the given user.
10215     */
10216    private int getTargetSdk(String packageName, int userId) {
10217        final ApplicationInfo ai;
10218        try {
10219            ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
10220            final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
10221            return targetSdkVersion;
10222        } catch (RemoteException e) {
10223            // Shouldn't happen
10224            return 0;
10225        }
10226    }
10227
10228    @Override
10229    public boolean isManagedProfile(ComponentName admin) {
10230        enforceProfileOrDeviceOwner(admin);
10231        return isManagedProfile(mInjector.userHandleGetCallingUserId());
10232    }
10233
10234    @Override
10235    public boolean isSystemOnlyUser(ComponentName admin) {
10236        synchronized (this) {
10237            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10238        }
10239        final int callingUserId = mInjector.userHandleGetCallingUserId();
10240        return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
10241    }
10242
10243    @Override
10244    public void reboot(ComponentName admin) {
10245        Preconditions.checkNotNull(admin);
10246        // Make sure caller has DO.
10247        synchronized (this) {
10248            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10249        }
10250        long ident = mInjector.binderClearCallingIdentity();
10251        try {
10252            // Make sure there are no ongoing calls on the device.
10253            if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
10254                throw new IllegalStateException("Cannot be called with ongoing call on the device");
10255            }
10256            mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
10257        } finally {
10258            mInjector.binderRestoreCallingIdentity(ident);
10259        }
10260    }
10261
10262    @Override
10263    public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
10264        if (!mHasFeature) {
10265            return;
10266        }
10267        Preconditions.checkNotNull(who, "ComponentName is null");
10268        final int userHandle = mInjector.userHandleGetCallingUserId();
10269        synchronized (this) {
10270            ActiveAdmin admin = getActiveAdminForUidLocked(who,
10271                    mInjector.binderGetCallingUid());
10272            if (!TextUtils.equals(admin.shortSupportMessage, message)) {
10273                admin.shortSupportMessage = message;
10274                saveSettingsLocked(userHandle);
10275            }
10276        }
10277    }
10278
10279    @Override
10280    public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
10281        if (!mHasFeature) {
10282            return null;
10283        }
10284        Preconditions.checkNotNull(who, "ComponentName is null");
10285        synchronized (this) {
10286            ActiveAdmin admin = getActiveAdminForUidLocked(who,
10287                    mInjector.binderGetCallingUid());
10288            return admin.shortSupportMessage;
10289        }
10290    }
10291
10292    @Override
10293    public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
10294        if (!mHasFeature) {
10295            return;
10296        }
10297        Preconditions.checkNotNull(who, "ComponentName is null");
10298        final int userHandle = mInjector.userHandleGetCallingUserId();
10299        synchronized (this) {
10300            ActiveAdmin admin = getActiveAdminForUidLocked(who,
10301                    mInjector.binderGetCallingUid());
10302            if (!TextUtils.equals(admin.longSupportMessage, message)) {
10303                admin.longSupportMessage = message;
10304                saveSettingsLocked(userHandle);
10305            }
10306        }
10307    }
10308
10309    @Override
10310    public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
10311        if (!mHasFeature) {
10312            return null;
10313        }
10314        Preconditions.checkNotNull(who, "ComponentName is null");
10315        synchronized (this) {
10316            ActiveAdmin admin = getActiveAdminForUidLocked(who,
10317                    mInjector.binderGetCallingUid());
10318            return admin.longSupportMessage;
10319        }
10320    }
10321
10322    @Override
10323    public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
10324        if (!mHasFeature) {
10325            return null;
10326        }
10327        Preconditions.checkNotNull(who, "ComponentName is null");
10328        if (!isCallerWithSystemUid()) {
10329            throw new SecurityException("Only the system can query support message for user");
10330        }
10331        synchronized (this) {
10332            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
10333            if (admin != null) {
10334                return admin.shortSupportMessage;
10335            }
10336        }
10337        return null;
10338    }
10339
10340    @Override
10341    public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
10342        if (!mHasFeature) {
10343            return null;
10344        }
10345        Preconditions.checkNotNull(who, "ComponentName is null");
10346        if (!isCallerWithSystemUid()) {
10347            throw new SecurityException("Only the system can query support message for user");
10348        }
10349        synchronized (this) {
10350            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
10351            if (admin != null) {
10352                return admin.longSupportMessage;
10353            }
10354        }
10355        return null;
10356    }
10357
10358    @Override
10359    public void setOrganizationColor(@NonNull ComponentName who, int color) {
10360        if (!mHasFeature) {
10361            return;
10362        }
10363        Preconditions.checkNotNull(who, "ComponentName is null");
10364        final int userHandle = mInjector.userHandleGetCallingUserId();
10365        enforceManagedProfile(userHandle, "set organization color");
10366        synchronized (this) {
10367            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10368                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10369            admin.organizationColor = color;
10370            saveSettingsLocked(userHandle);
10371        }
10372    }
10373
10374    @Override
10375    public void setOrganizationColorForUser(int color, int userId) {
10376        if (!mHasFeature) {
10377            return;
10378        }
10379        enforceFullCrossUsersPermission(userId);
10380        enforceManageUsers();
10381        enforceManagedProfile(userId, "set organization color");
10382        synchronized (this) {
10383            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
10384            admin.organizationColor = color;
10385            saveSettingsLocked(userId);
10386        }
10387    }
10388
10389    @Override
10390    public int getOrganizationColor(@NonNull ComponentName who) {
10391        if (!mHasFeature) {
10392            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
10393        }
10394        Preconditions.checkNotNull(who, "ComponentName is null");
10395        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
10396        synchronized (this) {
10397            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10398                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10399            return admin.organizationColor;
10400        }
10401    }
10402
10403    @Override
10404    public int getOrganizationColorForUser(int userHandle) {
10405        if (!mHasFeature) {
10406            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
10407        }
10408        enforceFullCrossUsersPermission(userHandle);
10409        enforceManagedProfile(userHandle, "get organization color");
10410        synchronized (this) {
10411            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
10412            return (profileOwner != null)
10413                    ? profileOwner.organizationColor
10414                    : ActiveAdmin.DEF_ORGANIZATION_COLOR;
10415        }
10416    }
10417
10418    @Override
10419    public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
10420        if (!mHasFeature) {
10421            return;
10422        }
10423        Preconditions.checkNotNull(who, "ComponentName is null");
10424        final int userHandle = mInjector.userHandleGetCallingUserId();
10425
10426        synchronized (this) {
10427            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10428                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10429            if (!TextUtils.equals(admin.organizationName, text)) {
10430                admin.organizationName = (text == null || text.length() == 0)
10431                        ? null : text.toString();
10432                saveSettingsLocked(userHandle);
10433            }
10434        }
10435    }
10436
10437    @Override
10438    public CharSequence getOrganizationName(@NonNull ComponentName who) {
10439        if (!mHasFeature) {
10440            return null;
10441        }
10442        Preconditions.checkNotNull(who, "ComponentName is null");
10443        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
10444        synchronized(this) {
10445            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10446                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10447            return admin.organizationName;
10448        }
10449    }
10450
10451    @Override
10452    public CharSequence getDeviceOwnerOrganizationName() {
10453        if (!mHasFeature) {
10454            return null;
10455        }
10456        enforceDeviceOwnerOrManageUsers();
10457        synchronized(this) {
10458            final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
10459            return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
10460        }
10461    }
10462
10463    @Override
10464    public CharSequence getOrganizationNameForUser(int userHandle) {
10465        if (!mHasFeature) {
10466            return null;
10467        }
10468        enforceFullCrossUsersPermission(userHandle);
10469        enforceManagedProfile(userHandle, "get organization name");
10470        synchronized (this) {
10471            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
10472            return (profileOwner != null)
10473                    ? profileOwner.organizationName
10474                    : null;
10475        }
10476    }
10477
10478    @Override
10479    public void setAffiliationIds(ComponentName admin, List<String> ids) {
10480        if (!mHasFeature) {
10481            return;
10482        }
10483        if (ids == null) {
10484            throw new IllegalArgumentException("ids must not be null");
10485        }
10486        for (String id : ids) {
10487            if (TextUtils.isEmpty(id)) {
10488                throw new IllegalArgumentException("ids must not contain empty string");
10489            }
10490        }
10491
10492        final Set<String> affiliationIds = new ArraySet<>(ids);
10493        final int callingUserId = mInjector.userHandleGetCallingUserId();
10494        synchronized (this) {
10495            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10496            getUserData(callingUserId).mAffiliationIds = affiliationIds;
10497            saveSettingsLocked(callingUserId);
10498            if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
10499                // Affiliation ids specified by the device owner are additionally stored in
10500                // UserHandle.USER_SYSTEM's DevicePolicyData.
10501                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
10502                saveSettingsLocked(UserHandle.USER_SYSTEM);
10503            }
10504
10505            // Affiliation status for any user, not just the calling user, might have changed.
10506            // The device owner user will still be affiliated after changing its affiliation ids,
10507            // but as a result of that other users might become affiliated or un-affiliated.
10508            maybePauseDeviceWideLoggingLocked();
10509            maybeResumeDeviceWideLoggingLocked();
10510            maybeClearLockTaskPolicyLocked();
10511        }
10512    }
10513
10514    @Override
10515    public List<String> getAffiliationIds(ComponentName admin) {
10516        if (!mHasFeature) {
10517            return Collections.emptyList();
10518        }
10519
10520        Preconditions.checkNotNull(admin);
10521        synchronized (this) {
10522            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10523            return new ArrayList<String>(
10524                    getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds);
10525        }
10526    }
10527
10528    @Override
10529    public boolean isAffiliatedUser() {
10530        if (!mHasFeature) {
10531            return false;
10532        }
10533
10534        synchronized (this) {
10535            return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
10536        }
10537    }
10538
10539    private boolean isUserAffiliatedWithDeviceLocked(int userId) {
10540        if (!mOwners.hasDeviceOwner()) {
10541            return false;
10542        }
10543        if (userId == mOwners.getDeviceOwnerUserId()) {
10544            // The user that the DO is installed on is always affiliated with the device.
10545            return true;
10546        }
10547        if (userId == UserHandle.USER_SYSTEM) {
10548            // The system user is always affiliated in a DO device, even if the DO is set on a
10549            // different user. This could be the case if the DO is set in the primary user
10550            // of a split user device.
10551            return true;
10552        }
10553        final ComponentName profileOwner = getProfileOwner(userId);
10554        if (profileOwner == null) {
10555            return false;
10556        }
10557        final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
10558        final Set<String> deviceAffiliationIds =
10559                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
10560        for (String id : userAffiliationIds) {
10561            if (deviceAffiliationIds.contains(id)) {
10562                return true;
10563            }
10564        }
10565        return false;
10566    }
10567
10568    private boolean areAllUsersAffiliatedWithDeviceLocked() {
10569        final long ident = mInjector.binderClearCallingIdentity();
10570        try {
10571            final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
10572            for (int i = 0; i < userInfos.size(); i++) {
10573                int userId = userInfos.get(i).id;
10574                if (!isUserAffiliatedWithDeviceLocked(userId)) {
10575                    Slog.d(LOG_TAG, "User id " + userId + " not affiliated.");
10576                    return false;
10577                }
10578            }
10579        } finally {
10580            mInjector.binderRestoreCallingIdentity(ident);
10581        }
10582
10583        return true;
10584    }
10585
10586    @Override
10587    public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
10588        if (!mHasFeature) {
10589            return;
10590        }
10591        Preconditions.checkNotNull(admin);
10592
10593        synchronized (this) {
10594            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10595            if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
10596                return;
10597            }
10598            mInjector.securityLogSetLoggingEnabledProperty(enabled);
10599            if (enabled) {
10600                mSecurityLogMonitor.start();
10601                maybePauseDeviceWideLoggingLocked();
10602            } else {
10603                mSecurityLogMonitor.stop();
10604            }
10605        }
10606    }
10607
10608    @Override
10609    public boolean isSecurityLoggingEnabled(ComponentName admin) {
10610        if (!mHasFeature) {
10611            return false;
10612        }
10613
10614        synchronized (this) {
10615            if (!isCallerWithSystemUid()) {
10616                Preconditions.checkNotNull(admin);
10617                getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10618            }
10619            return mInjector.securityLogGetLoggingEnabledProperty();
10620        }
10621    }
10622
10623    private synchronized void recordSecurityLogRetrievalTime() {
10624        final long currentTime = System.currentTimeMillis();
10625        DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
10626        if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
10627            policyData.mLastSecurityLogRetrievalTime = currentTime;
10628            saveSettingsLocked(UserHandle.USER_SYSTEM);
10629        }
10630    }
10631
10632    @Override
10633    public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
10634        if (!mHasFeature) {
10635            return null;
10636        }
10637
10638        Preconditions.checkNotNull(admin);
10639        ensureDeviceOwnerAndAllUsersAffiliated(admin);
10640
10641        if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
10642                || !mInjector.securityLogGetLoggingEnabledProperty()) {
10643            return null;
10644        }
10645
10646        recordSecurityLogRetrievalTime();
10647
10648        ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
10649        try {
10650            SecurityLog.readPreviousEvents(output);
10651            return new ParceledListSlice<SecurityEvent>(output);
10652        } catch (IOException e) {
10653            Slog.w(LOG_TAG, "Fail to read previous events" , e);
10654            return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
10655        }
10656    }
10657
10658    @Override
10659    public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
10660        if (!mHasFeature) {
10661            return null;
10662        }
10663
10664        Preconditions.checkNotNull(admin);
10665        ensureDeviceOwnerAndAllUsersAffiliated(admin);
10666
10667        if (!mInjector.securityLogGetLoggingEnabledProperty()) {
10668            return null;
10669        }
10670
10671        recordSecurityLogRetrievalTime();
10672
10673        List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
10674        return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
10675    }
10676
10677    private void enforceCanManageDeviceAdmin() {
10678        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
10679                null);
10680    }
10681
10682    private void enforceCanManageProfileAndDeviceOwners() {
10683        mContext.enforceCallingOrSelfPermission(
10684                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
10685    }
10686
10687    private void enforceCallerSystemUserHandle() {
10688        final int callingUid = mInjector.binderGetCallingUid();
10689        final int userId = UserHandle.getUserId(callingUid);
10690        if (userId != UserHandle.USER_SYSTEM) {
10691            throw new SecurityException("Caller has to be in user 0");
10692        }
10693    }
10694
10695    @Override
10696    public boolean isUninstallInQueue(final String packageName) {
10697        enforceCanManageDeviceAdmin();
10698        final int userId = mInjector.userHandleGetCallingUserId();
10699        Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10700        synchronized (this) {
10701            return mPackagesToRemove.contains(packageUserPair);
10702        }
10703    }
10704
10705    @Override
10706    public void uninstallPackageWithActiveAdmins(final String packageName) {
10707        enforceCanManageDeviceAdmin();
10708        Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
10709
10710        final int userId = mInjector.userHandleGetCallingUserId();
10711
10712        enforceUserUnlocked(userId);
10713
10714        final ComponentName profileOwner = getProfileOwner(userId);
10715        if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
10716            throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
10717        }
10718
10719        final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
10720        if (getDeviceOwnerUserId() == userId && deviceOwner != null
10721                && packageName.equals(deviceOwner.getPackageName())) {
10722            throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
10723        }
10724
10725        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10726        synchronized (this) {
10727            mPackagesToRemove.add(packageUserPair);
10728        }
10729
10730        // All active admins on the user.
10731        final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
10732
10733        // Active admins in the target package.
10734        final List<ComponentName> packageActiveAdmins = new ArrayList<>();
10735        if (allActiveAdmins != null) {
10736            for (ComponentName activeAdmin : allActiveAdmins) {
10737                if (packageName.equals(activeAdmin.getPackageName())) {
10738                    packageActiveAdmins.add(activeAdmin);
10739                    removeActiveAdmin(activeAdmin, userId);
10740                }
10741            }
10742        }
10743        if (packageActiveAdmins.size() == 0) {
10744            startUninstallIntent(packageName, userId);
10745        } else {
10746            mHandler.postDelayed(new Runnable() {
10747                @Override
10748                public void run() {
10749                    for (ComponentName activeAdmin : packageActiveAdmins) {
10750                        removeAdminArtifacts(activeAdmin, userId);
10751                    }
10752                    startUninstallIntent(packageName, userId);
10753                }
10754            }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
10755        }
10756    }
10757
10758    @Override
10759    public boolean isDeviceProvisioned() {
10760        synchronized (this) {
10761            return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
10762        }
10763    }
10764
10765    private boolean isCurrentUserDemo() {
10766        if (UserManager.isDeviceInDemoMode(mContext)) {
10767            final int userId = mInjector.userHandleGetCallingUserId();
10768            final long callingIdentity = mInjector.binderClearCallingIdentity();
10769            try {
10770                return mUserManager.getUserInfo(userId).isDemo();
10771            } finally {
10772                mInjector.binderRestoreCallingIdentity(callingIdentity);
10773            }
10774        }
10775        return false;
10776    }
10777
10778    private void removePackageIfRequired(final String packageName, final int userId) {
10779        if (!packageHasActiveAdmins(packageName, userId)) {
10780            // Will not do anything if uninstall was not requested or was already started.
10781            startUninstallIntent(packageName, userId);
10782        }
10783    }
10784
10785    private void startUninstallIntent(final String packageName, final int userId) {
10786        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10787        synchronized (this) {
10788            if (!mPackagesToRemove.contains(packageUserPair)) {
10789                // Do nothing if uninstall was not requested or was already started.
10790                return;
10791            }
10792            mPackagesToRemove.remove(packageUserPair);
10793        }
10794        try {
10795            if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
10796                // Package does not exist. Nothing to do.
10797                return;
10798            }
10799        } catch (RemoteException re) {
10800            Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
10801        }
10802
10803        try { // force stop the package before uninstalling
10804            mInjector.getIActivityManager().forceStopPackage(packageName, userId);
10805        } catch (RemoteException re) {
10806            Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
10807        }
10808        final Uri packageURI = Uri.parse("package:" + packageName);
10809        final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
10810        uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
10811        mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
10812    }
10813
10814    /**
10815     * Removes the admin from the policy. Ideally called after the admin's
10816     * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
10817     *
10818     * @param adminReceiver The admin to remove
10819     * @param userHandle The user for which this admin has to be removed.
10820     */
10821    private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
10822        synchronized (this) {
10823            final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
10824            if (admin == null) {
10825                return;
10826            }
10827            final DevicePolicyData policy = getUserData(userHandle);
10828            final boolean doProxyCleanup = admin.info.usesPolicy(
10829                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
10830            policy.mAdminList.remove(admin);
10831            policy.mAdminMap.remove(adminReceiver);
10832            validatePasswordOwnerLocked(policy);
10833            if (doProxyCleanup) {
10834                resetGlobalProxyLocked(policy);
10835            }
10836            saveSettingsLocked(userHandle);
10837            updateMaximumTimeToLockLocked(userHandle);
10838            policy.mRemovingAdmins.remove(adminReceiver);
10839
10840            Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
10841        }
10842        // The removed admin might have disabled camera, so update user
10843        // restrictions.
10844        pushUserRestrictions(userHandle);
10845    }
10846
10847    @Override
10848    public void setDeviceProvisioningConfigApplied() {
10849        enforceManageUsers();
10850        synchronized (this) {
10851            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
10852            policy.mDeviceProvisioningConfigApplied = true;
10853            saveSettingsLocked(UserHandle.USER_SYSTEM);
10854        }
10855    }
10856
10857    @Override
10858    public boolean isDeviceProvisioningConfigApplied() {
10859        enforceManageUsers();
10860        synchronized (this) {
10861            final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
10862            return policy.mDeviceProvisioningConfigApplied;
10863        }
10864    }
10865
10866    /**
10867     * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
10868     *
10869     * It's added for testing only. Please use this API carefully if it's used by other system app
10870     * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
10871     * apps.
10872     */
10873    @Override
10874    public void forceUpdateUserSetupComplete() {
10875        enforceCanManageProfileAndDeviceOwners();
10876        enforceCallerSystemUserHandle();
10877        // no effect if it's called from user build
10878        if (!mInjector.isBuildDebuggable()) {
10879            return;
10880        }
10881        final int userId = UserHandle.USER_SYSTEM;
10882        boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
10883                Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
10884        DevicePolicyData policy = getUserData(userId);
10885        policy.mUserSetupComplete = isUserCompleted;
10886        synchronized (this) {
10887            saveSettingsLocked(userId);
10888        }
10889    }
10890
10891    // TODO(b/22388012): When backup is available for secondary users and profiles, consider
10892    // whether there are any privacy/security implications of enabling the backup service here
10893    // if there are other users or profiles unmanaged or managed by a different entity (i.e. not
10894    // affiliated).
10895    @Override
10896    public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
10897        if (!mHasFeature) {
10898            return;
10899        }
10900        Preconditions.checkNotNull(admin);
10901        synchronized (this) {
10902            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10903        }
10904
10905        final long ident = mInjector.binderClearCallingIdentity();
10906        try {
10907            IBackupManager ibm = mInjector.getIBackupManager();
10908            if (ibm != null) {
10909                ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
10910            }
10911        } catch (RemoteException e) {
10912            throw new IllegalStateException(
10913                "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
10914        } finally {
10915            mInjector.binderRestoreCallingIdentity(ident);
10916        }
10917    }
10918
10919    @Override
10920    public boolean isBackupServiceEnabled(ComponentName admin) {
10921        Preconditions.checkNotNull(admin);
10922        if (!mHasFeature) {
10923            return true;
10924        }
10925        synchronized (this) {
10926            try {
10927                getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10928                IBackupManager ibm = mInjector.getIBackupManager();
10929                return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
10930            } catch (RemoteException e) {
10931                throw new IllegalStateException("Failed requesting backup service state.", e);
10932            }
10933        }
10934    }
10935
10936    @Override
10937    public boolean bindDeviceAdminServiceAsUser(
10938            @NonNull ComponentName admin, @NonNull IApplicationThread caller,
10939            @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
10940            @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
10941        if (!mHasFeature) {
10942            return false;
10943        }
10944        Preconditions.checkNotNull(admin);
10945        Preconditions.checkNotNull(caller);
10946        Preconditions.checkNotNull(serviceIntent);
10947        Preconditions.checkArgument(
10948                serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
10949                "Service intent must be explicit (with a package name or component): "
10950                        + serviceIntent);
10951        Preconditions.checkNotNull(connection);
10952        Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
10953                "target user id must be different from the calling user id");
10954
10955        if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
10956            throw new SecurityException("Not allowed to bind to target user id");
10957        }
10958
10959        final String targetPackage;
10960        synchronized (this) {
10961            targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
10962        }
10963
10964        final long callingIdentity = mInjector.binderClearCallingIdentity();
10965        try {
10966            // Validate and sanitize the incoming service intent.
10967            final Intent sanitizedIntent =
10968                    createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
10969            if (sanitizedIntent == null) {
10970                // Fail, cannot lookup the target service.
10971                return false;
10972            }
10973            // Ask ActivityManager to bind it. Notice that we are binding the service with the
10974            // caller app instead of DevicePolicyManagerService.
10975            return mInjector.getIActivityManager().bindService(
10976                    caller, activtiyToken, serviceIntent,
10977                    serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
10978                    connection, flags, mContext.getOpPackageName(),
10979                    targetUserId) != 0;
10980        } catch (RemoteException ex) {
10981            // Same process, should not happen.
10982        } finally {
10983            mInjector.binderRestoreCallingIdentity(callingIdentity);
10984        }
10985
10986        // Failed to bind.
10987        return false;
10988    }
10989
10990    @Override
10991    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
10992        if (!mHasFeature) {
10993            return Collections.emptyList();
10994        }
10995        Preconditions.checkNotNull(admin);
10996
10997        synchronized (this) {
10998            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10999
11000            final int callingUserId = mInjector.userHandleGetCallingUserId();
11001            final long callingIdentity = mInjector.binderClearCallingIdentity();
11002            try {
11003                ArrayList<UserHandle> targetUsers = new ArrayList<>();
11004                if (!isDeviceOwner(admin, callingUserId)) {
11005                    // Profile owners can only bind to the device owner.
11006                    if (canUserBindToDeviceOwnerLocked(callingUserId)) {
11007                        targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
11008                    }
11009                } else {
11010                    // Caller is the device owner: Look for profile owners that it can bind to.
11011                    final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
11012                    for (int i = 0; i < userInfos.size(); i++) {
11013                        final int userId = userInfos.get(i).id;
11014                        if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
11015                            targetUsers.add(UserHandle.of(userId));
11016                        }
11017                    }
11018                }
11019
11020                return targetUsers;
11021            } finally {
11022                mInjector.binderRestoreCallingIdentity(callingIdentity);
11023            }
11024        }
11025    }
11026
11027    private boolean canUserBindToDeviceOwnerLocked(int userId) {
11028        // There has to be a device owner, under another user id.
11029        if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
11030            return false;
11031        }
11032
11033        // The user must have a profile owner that belongs to the same package as the device owner.
11034        if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
11035                mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
11036            return false;
11037        }
11038
11039        // The user must be affiliated.
11040        return isUserAffiliatedWithDeviceLocked(userId);
11041    }
11042
11043    /**
11044     * Return true if a given user has any accounts that'll prevent installing a device or profile
11045     * owner {@code owner}.
11046     * - If the user has no accounts, then return false.
11047     * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
11048     * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
11049     *   ..._DISALLOWED, return true.
11050     * - Otherwise return false.
11051     *
11052     * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
11053     * when the caller is not ADB.
11054     *
11055     * DO NOT CALL IT WITH THE DPMS LOCK HELD.
11056     */
11057    private boolean hasIncompatibleAccountsOrNonAdbNoLock(
11058            int userId, @Nullable ComponentName owner) {
11059        if (!isAdb()) {
11060            return true;
11061        }
11062        wtfIfInLock();
11063
11064        final long token = mInjector.binderClearCallingIdentity();
11065        try {
11066            final AccountManager am = AccountManager.get(mContext);
11067            final Account accounts[] = am.getAccountsAsUser(userId);
11068            if (accounts.length == 0) {
11069                return false;
11070            }
11071            synchronized (this) {
11072                if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
11073                    Log.w(LOG_TAG,
11074                            "Non test-only owner can't be installed with existing accounts.");
11075                    return true;
11076                }
11077            }
11078
11079            final String[] feature_allow =
11080                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
11081            final String[] feature_disallow =
11082                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
11083
11084            boolean compatible = true;
11085            for (Account account : accounts) {
11086                if (hasAccountFeatures(am, account, feature_disallow)) {
11087                    Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
11088                    compatible = false;
11089                    break;
11090                }
11091                if (!hasAccountFeatures(am, account, feature_allow)) {
11092                    Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
11093                    compatible = false;
11094                    break;
11095                }
11096            }
11097            if (compatible) {
11098                Log.w(LOG_TAG, "All accounts are compatible");
11099            } else {
11100                Log.e(LOG_TAG, "Found incompatible accounts");
11101            }
11102            return !compatible;
11103        } finally {
11104            mInjector.binderRestoreCallingIdentity(token);
11105        }
11106    }
11107
11108    private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
11109        try {
11110            return am.hasFeatures(account, features, null, null).getResult();
11111        } catch (Exception e) {
11112            Log.w(LOG_TAG, "Failed to get account feature", e);
11113            return false;
11114        }
11115    }
11116
11117    private boolean isAdb() {
11118        final int callingUid = mInjector.binderGetCallingUid();
11119        return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
11120    }
11121
11122    @Override
11123    public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
11124        if (!mHasFeature) {
11125            return;
11126        }
11127        Preconditions.checkNotNull(admin);
11128        getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11129
11130        if (enabled == isNetworkLoggingEnabledInternalLocked()) {
11131            // already in the requested state
11132            return;
11133        }
11134        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11135        deviceOwner.isNetworkLoggingEnabled = enabled;
11136        if (!enabled) {
11137            deviceOwner.numNetworkLoggingNotifications = 0;
11138            deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
11139        }
11140        saveSettingsLocked(mInjector.userHandleGetCallingUserId());
11141
11142        setNetworkLoggingActiveInternal(enabled);
11143    }
11144
11145    private synchronized void setNetworkLoggingActiveInternal(boolean active) {
11146        final long callingIdentity = mInjector.binderClearCallingIdentity();
11147        try {
11148            if (active) {
11149                mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
11150                if (!mNetworkLogger.startNetworkLogging()) {
11151                    mNetworkLogger = null;
11152                    Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
11153                            + " service not being available yet.");
11154                }
11155                maybePauseDeviceWideLoggingLocked();
11156                sendNetworkLoggingNotificationLocked();
11157            } else {
11158                if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
11159                    Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
11160                            + " service not being available yet.");
11161                }
11162                mNetworkLogger = null;
11163                mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING);
11164            }
11165        } finally {
11166            mInjector.binderRestoreCallingIdentity(callingIdentity);
11167        }
11168    }
11169
11170    /** Pauses security and network logging if there are unaffiliated users on the device */
11171    private void maybePauseDeviceWideLoggingLocked() {
11172        if (!areAllUsersAffiliatedWithDeviceLocked()) {
11173            Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be "
11174                    + "paused if enabled.");
11175            mSecurityLogMonitor.pause();
11176            if (mNetworkLogger != null) {
11177                mNetworkLogger.pause();
11178            }
11179        }
11180    }
11181
11182    /** Resumes security and network logging (if they are enabled) if all users are affiliated */
11183    private void maybeResumeDeviceWideLoggingLocked() {
11184        if (areAllUsersAffiliatedWithDeviceLocked()) {
11185            final long ident = mInjector.binderClearCallingIdentity();
11186            try {
11187                mSecurityLogMonitor.resume();
11188                if (mNetworkLogger != null) {
11189                    mNetworkLogger.resume();
11190                }
11191            } finally {
11192                mInjector.binderRestoreCallingIdentity(ident);
11193            }
11194        }
11195    }
11196
11197    /** Deletes any security and network logs that might have been collected so far */
11198    private void discardDeviceWideLogsLocked() {
11199        mSecurityLogMonitor.discardLogs();
11200        if (mNetworkLogger != null) {
11201            mNetworkLogger.discardLogs();
11202        }
11203        // TODO: We should discard pre-boot security logs here too, as otherwise those
11204        // logs (which might contain data from the user just removed) will be
11205        // available after next boot.
11206    }
11207
11208    @Override
11209    public boolean isNetworkLoggingEnabled(ComponentName admin) {
11210        if (!mHasFeature) {
11211            return false;
11212        }
11213        synchronized (this) {
11214            enforceDeviceOwnerOrManageUsers();
11215            return isNetworkLoggingEnabledInternalLocked();
11216        }
11217    }
11218
11219    private boolean isNetworkLoggingEnabledInternalLocked() {
11220        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11221        return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
11222    }
11223
11224    /*
11225     * A maximum of 1200 events are returned, and the total marshalled size is in the order of
11226     * 100kB, so returning a List instead of ParceledListSlice is acceptable.
11227     * Ideally this would be done with ParceledList, however it only supports homogeneous types.
11228     *
11229     * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
11230     */
11231    @Override
11232    public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) {
11233        if (!mHasFeature) {
11234            return null;
11235        }
11236        Preconditions.checkNotNull(admin);
11237        ensureDeviceOwnerAndAllUsersAffiliated(admin);
11238
11239        synchronized (this) {
11240            if (mNetworkLogger == null
11241                    || !isNetworkLoggingEnabledInternalLocked()) {
11242                return null;
11243            }
11244
11245            final long currentTime = System.currentTimeMillis();
11246            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
11247            if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
11248                policyData.mLastNetworkLogsRetrievalTime = currentTime;
11249                saveSettingsLocked(UserHandle.USER_SYSTEM);
11250            }
11251            return mNetworkLogger.retrieveLogs(batchToken);
11252        }
11253    }
11254
11255    private void sendNetworkLoggingNotificationLocked() {
11256        final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11257        if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
11258            return;
11259        }
11260        if (deviceOwner.numNetworkLoggingNotifications >=
11261                ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
11262            return;
11263        }
11264        final long now = System.currentTimeMillis();
11265        if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
11266            return;
11267        }
11268        deviceOwner.numNetworkLoggingNotifications++;
11269        if (deviceOwner.numNetworkLoggingNotifications
11270                >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
11271            deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
11272        } else {
11273            deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
11274        }
11275        final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
11276        intent.setPackage("com.android.systemui");
11277        final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
11278                UserHandle.CURRENT);
11279        Notification notification =
11280                new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
11281                .setSmallIcon(R.drawable.ic_info_outline)
11282                .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
11283                .setContentText(mContext.getString(R.string.network_logging_notification_text))
11284                .setTicker(mContext.getString(R.string.network_logging_notification_title))
11285                .setShowWhen(true)
11286                .setContentIntent(pendingIntent)
11287                .setStyle(new Notification.BigTextStyle()
11288                        .bigText(mContext.getString(R.string.network_logging_notification_text)))
11289                .build();
11290        mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification);
11291        saveSettingsLocked(mOwners.getDeviceOwnerUserId());
11292    }
11293
11294    /**
11295     * Return the package name of owner in a given user.
11296     */
11297    private String getOwnerPackageNameForUserLocked(int userId) {
11298        return mOwners.getDeviceOwnerUserId() == userId
11299                ? mOwners.getDeviceOwnerPackageName()
11300                : mOwners.getProfileOwnerPackage(userId);
11301    }
11302
11303    /**
11304     * @param rawIntent Original service intent specified by caller. It must be explicit.
11305     * @param expectedPackageName The expected package name of the resolved service.
11306     * @return Intent that have component explicitly set. {@code null} if no service is resolved
11307     *     with the given intent.
11308     * @throws SecurityException if the intent is resolved to an invalid service.
11309     */
11310    private Intent createCrossUserServiceIntent(
11311            @NonNull Intent rawIntent, @NonNull String expectedPackageName,
11312            @UserIdInt int targetUserId) throws RemoteException, SecurityException {
11313        ResolveInfo info = mIPackageManager.resolveService(
11314                rawIntent,
11315                rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
11316                0,  // flags
11317                targetUserId);
11318        if (info == null || info.serviceInfo == null) {
11319            Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent
11320                    + " or user " + targetUserId + " is not running");
11321            return null;
11322        }
11323        if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
11324            throw new SecurityException("Only allow to bind service in " + expectedPackageName);
11325        }
11326        // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
11327        if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
11328            throw new SecurityException(
11329                    "Service must be protected by BIND_DEVICE_ADMIN permission");
11330        }
11331        // It is the system server to bind the service, it would be extremely dangerous if it
11332        // can be exploited to bind any service. Set the component explicitly to make sure we
11333        // do not bind anything accidentally.
11334        rawIntent.setComponent(info.serviceInfo.getComponentName());
11335        return rawIntent;
11336    }
11337
11338    @Override
11339    public long getLastSecurityLogRetrievalTime() {
11340        enforceDeviceOwnerOrManageUsers();
11341        return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
11342     }
11343
11344    @Override
11345    public long getLastBugReportRequestTime() {
11346        enforceDeviceOwnerOrManageUsers();
11347        return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
11348     }
11349
11350    @Override
11351    public long getLastNetworkLogRetrievalTime() {
11352        enforceDeviceOwnerOrManageUsers();
11353        return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime;
11354    }
11355
11356    @Override
11357    public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
11358        if (!mHasFeature) {
11359            return false;
11360        }
11361        if (token == null || token.length < 32) {
11362            throw new IllegalArgumentException("token must be at least 32-byte long");
11363        }
11364        synchronized (this) {
11365            final int userHandle = mInjector.userHandleGetCallingUserId();
11366            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11367
11368            DevicePolicyData policy = getUserData(userHandle);
11369            long ident = mInjector.binderClearCallingIdentity();
11370            try {
11371                if (policy.mPasswordTokenHandle != 0) {
11372                    mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle);
11373                }
11374
11375                policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, userHandle);
11376                saveSettingsLocked(userHandle);
11377                return policy.mPasswordTokenHandle != 0;
11378            } finally {
11379                mInjector.binderRestoreCallingIdentity(ident);
11380            }
11381        }
11382    }
11383
11384    @Override
11385    public boolean clearResetPasswordToken(ComponentName admin) {
11386        if (!mHasFeature) {
11387            return false;
11388        }
11389        synchronized (this) {
11390            final int userHandle = mInjector.userHandleGetCallingUserId();
11391            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11392
11393            DevicePolicyData policy = getUserData(userHandle);
11394            if (policy.mPasswordTokenHandle != 0) {
11395                long ident = mInjector.binderClearCallingIdentity();
11396                try {
11397                    boolean result = mLockPatternUtils.removeEscrowToken(
11398                            policy.mPasswordTokenHandle, userHandle);
11399                    policy.mPasswordTokenHandle = 0;
11400                    saveSettingsLocked(userHandle);
11401                    return result;
11402                } finally {
11403                    mInjector.binderRestoreCallingIdentity(ident);
11404                }
11405            }
11406        }
11407        return false;
11408    }
11409
11410    @Override
11411    public boolean isResetPasswordTokenActive(ComponentName admin) {
11412        synchronized (this) {
11413            final int userHandle = mInjector.userHandleGetCallingUserId();
11414            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11415
11416            DevicePolicyData policy = getUserData(userHandle);
11417            if (policy.mPasswordTokenHandle != 0) {
11418                long ident = mInjector.binderClearCallingIdentity();
11419                try {
11420                    return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle,
11421                            userHandle);
11422                } finally {
11423                    mInjector.binderRestoreCallingIdentity(ident);
11424                }
11425            }
11426        }
11427        return false;
11428    }
11429
11430    @Override
11431    public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token,
11432            int flags) {
11433        Preconditions.checkNotNull(token);
11434        synchronized (this) {
11435            final int userHandle = mInjector.userHandleGetCallingUserId();
11436            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11437
11438            DevicePolicyData policy = getUserData(userHandle);
11439            if (policy.mPasswordTokenHandle != 0) {
11440                final String password = passwordOrNull != null ? passwordOrNull : "";
11441                return resetPasswordInternal(password, policy.mPasswordTokenHandle, token,
11442                        flags, mInjector.binderGetCallingUid(), userHandle);
11443            } else {
11444                Slog.w(LOG_TAG, "No saved token handle");
11445            }
11446        }
11447        return false;
11448    }
11449
11450    @Override
11451    public boolean isCurrentInputMethodSetByOwner() {
11452        enforceProfileOwnerOrSystemUser();
11453        return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet;
11454    }
11455
11456    @Override
11457    public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
11458        final int userId = user.getIdentifier();
11459        enforceProfileOwnerOrFullCrossUsersPermission(userId);
11460        synchronized (this) {
11461            return new StringParceledListSlice(
11462                    new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));
11463        }
11464    }
11465
11466    @Override
11467    public boolean clearApplicationUserData(ComponentName admin, String packageName,
11468            IPackageDataObserver callback) {
11469        Preconditions.checkNotNull(admin, "ComponentName is null");
11470        synchronized (this) {
11471            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11472        }
11473        final int userId = UserHandle.getCallingUserId();
11474
11475        long ident = mInjector.binderClearCallingIdentity();
11476        try {
11477            return ActivityManager.getService().clearApplicationUserData(packageName, false,
11478                    callback, userId);
11479        } catch(RemoteException re) {
11480            // Same process, should not happen.
11481        } catch (SecurityException se) {
11482            // This can happen e.g. for device admin packages, do not throw out the exception,
11483            // because callers have no means to know beforehand for which packages this might
11484            // happen.
11485            Slog.w(LOG_TAG, "Not allowed to clear application user data for package " + packageName,
11486                    se);
11487        } finally {
11488            mInjector.binderRestoreCallingIdentity(ident);
11489        }
11490
11491        if (callback != null) {
11492            try {
11493                // If there was a throw above, we send back that removal failed
11494                callback.onRemoveCompleted(packageName, false);
11495            } catch (RemoteException re) {
11496                // Caller is no longer available, ignore
11497            }
11498        }
11499        return false;
11500    }
11501
11502    @Override
11503    public synchronized void setLogoutEnabled(ComponentName admin, boolean enabled) {
11504        if (!mHasFeature) {
11505            return;
11506        }
11507        Preconditions.checkNotNull(admin);
11508        getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11509
11510        if (enabled == isLogoutEnabledInternalLocked()) {
11511            // already in the requested state
11512            return;
11513        }
11514        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11515        deviceOwner.isLogoutEnabled = enabled;
11516        saveSettingsLocked(mInjector.userHandleGetCallingUserId());
11517    }
11518
11519    @Override
11520    public boolean isLogoutEnabled() {
11521        if (!mHasFeature) {
11522            return false;
11523        }
11524        synchronized (this) {
11525            return isLogoutEnabledInternalLocked();
11526        }
11527    }
11528
11529    private boolean isLogoutEnabledInternalLocked() {
11530        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11531        return (deviceOwner != null) && deviceOwner.isLogoutEnabled;
11532    }
11533
11534    @Override
11535    public List<String> getDisallowedSystemApps(ComponentName admin, int userId,
11536            String provisioningAction) throws RemoteException {
11537        enforceCanManageProfileAndDeviceOwners();
11538        return new ArrayList<>(
11539                mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction));
11540    }
11541}
11542