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