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