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