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