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