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