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