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