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