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