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