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