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