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