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