DevicePolicyManagerService.java revision 9bd54c1cd8dc365a2d07ff5563df6acec835be4d
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.BIND_DEVICE_ADMIN;
20import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
21import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
22import static android.app.ActivityManager.USER_OP_SUCCESS;
23import static android.app.admin.DeviceAdminReceiver.EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE;
24import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER;
25import static android.app.admin.DevicePolicyManager.CODE_ACCOUNTS_NOT_EMPTY;
26import static android.app.admin.DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED;
27import static android.app.admin.DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE;
28import static android.app.admin.DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED;
29import static android.app.admin.DevicePolicyManager.CODE_HAS_DEVICE_OWNER;
30import static android.app.admin.DevicePolicyManager.CODE_HAS_PAIRED;
31import static android.app.admin.DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED;
32import static android.app.admin.DevicePolicyManager.CODE_NONSYSTEM_USER_EXISTS;
33import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER;
34import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT;
35import static android.app.admin.DevicePolicyManager.CODE_OK;
36import static android.app.admin.DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
37import static android.app.admin.DevicePolicyManager.CODE_SYSTEM_USER;
38import static android.app.admin.DevicePolicyManager.CODE_USER_HAS_PROFILE_OWNER;
39import static android.app.admin.DevicePolicyManager.CODE_USER_NOT_RUNNING;
40import static android.app.admin.DevicePolicyManager.CODE_USER_SETUP_COMPLETED;
41import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
42import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL;
43import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
44import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP;
45import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE;
46import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES;
47import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS;
48import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT;
49import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
50import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
51import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
52import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
53import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED;
54import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
55import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
56import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
57import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
58import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
59import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
60import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
61
62import static android.provider.Telephony.Carriers.DPC_URI;
63import static android.provider.Telephony.Carriers.ENFORCE_KEY;
64import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI;
65
66import static com.android.internal.logging.nano.MetricsProto.MetricsEvent
67        .PROVISIONING_ENTRY_POINT_ADB;
68import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker
69        .STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
70
71import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
72import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
73
74import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER;
75import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER;
76
77import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
78import static org.xmlpull.v1.XmlPullParser.END_TAG;
79import static org.xmlpull.v1.XmlPullParser.TEXT;
80
81import android.Manifest.permission;
82import android.accessibilityservice.AccessibilityServiceInfo;
83import android.accounts.Account;
84import android.accounts.AccountManager;
85import android.annotation.NonNull;
86import android.annotation.Nullable;
87import android.annotation.UserIdInt;
88import android.app.Activity;
89import android.app.ActivityManager;
90import android.app.ActivityManagerInternal;
91import android.app.ActivityThread;
92import android.app.AlarmManager;
93import android.app.AppGlobals;
94import android.app.IActivityManager;
95import android.app.IApplicationThread;
96import android.app.IServiceConnection;
97import android.app.Notification;
98import android.app.NotificationManager;
99import android.app.PendingIntent;
100import android.app.StatusBarManager;
101import android.app.admin.DeviceAdminInfo;
102import android.app.admin.DeviceAdminReceiver;
103import android.app.admin.DevicePolicyManager;
104import android.app.admin.DevicePolicyManagerInternal;
105import android.app.admin.NetworkEvent;
106import android.app.admin.PasswordMetrics;
107import android.app.admin.SecurityLog;
108import android.app.admin.SecurityLog.SecurityEvent;
109import android.app.admin.SystemUpdateInfo;
110import android.app.admin.SystemUpdatePolicy;
111import android.app.backup.IBackupManager;
112import android.app.trust.TrustManager;
113import android.app.usage.UsageStatsManagerInternal;
114import android.content.BroadcastReceiver;
115import android.content.ComponentName;
116import android.content.ContentValues;
117import android.content.Context;
118import android.content.Intent;
119import android.content.IntentFilter;
120import android.content.pm.ActivityInfo;
121import android.content.pm.ApplicationInfo;
122import android.content.pm.IPackageDataObserver;
123import android.content.pm.IPackageManager;
124import android.content.pm.PackageInfo;
125import android.content.pm.PackageManager;
126import android.content.pm.PackageManager.NameNotFoundException;
127import android.content.pm.PackageManagerInternal;
128import android.content.pm.ParceledListSlice;
129import android.content.pm.PermissionInfo;
130import android.content.pm.ResolveInfo;
131import android.content.pm.ServiceInfo;
132import android.content.pm.StringParceledListSlice;
133import android.content.pm.UserInfo;
134import android.content.res.Resources;
135import android.database.ContentObserver;
136import android.database.Cursor;
137import android.graphics.Bitmap;
138import android.graphics.Color;
139import android.media.AudioManager;
140import android.media.IAudioService;
141import android.net.ConnectivityManager;
142import android.net.IIpConnectivityMetrics;
143import android.net.ProxyInfo;
144import android.net.Uri;
145import android.net.metrics.IpConnectivityLog;
146import android.net.wifi.WifiInfo;
147import android.net.wifi.WifiManager;
148import android.os.Binder;
149import android.os.Build;
150import android.os.Bundle;
151import android.os.Environment;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.ParcelFileDescriptor;
157import android.os.PersistableBundle;
158import android.os.PowerManager;
159import android.os.PowerManagerInternal;
160import android.os.Process;
161import android.os.RecoverySystem;
162import android.os.RemoteCallback;
163import android.os.RemoteException;
164import android.os.ServiceManager;
165import android.os.SystemClock;
166import android.os.SystemProperties;
167import android.os.UserHandle;
168import android.os.UserManager;
169import android.os.UserManagerInternal;
170import android.os.UserManagerInternal.UserRestrictionsListener;
171import android.os.storage.StorageManager;
172import android.provider.ContactsContract.QuickContact;
173import android.provider.ContactsInternal;
174import android.provider.Settings;
175import android.provider.Settings.Global;
176import android.security.IKeyChainAliasCallback;
177import android.security.IKeyChainService;
178import android.security.KeyChain;
179import android.security.KeyChain.KeyChainConnection;
180import android.security.KeyStore;
181import android.security.keymaster.KeymasterCertificateChain;
182import android.security.keystore.AttestationUtils;
183import android.security.keystore.KeyGenParameterSpec;
184import android.security.keystore.ParcelableKeyGenParameterSpec;
185import android.service.persistentdata.PersistentDataBlockManager;
186import android.telephony.TelephonyManager;
187import android.telephony.data.ApnSetting;
188import android.text.TextUtils;
189import android.util.ArrayMap;
190import android.util.ArraySet;
191import android.util.AtomicFile;
192import android.util.Log;
193import android.util.Pair;
194import android.util.Slog;
195import android.util.SparseArray;
196import android.util.Xml;
197import android.view.IWindowManager;
198import android.view.accessibility.AccessibilityManager;
199import android.view.accessibility.IAccessibilityManager;
200import android.view.inputmethod.InputMethodInfo;
201import android.view.inputmethod.InputMethodManager;
202
203import com.android.internal.R;
204import com.android.internal.annotations.GuardedBy;
205import com.android.internal.annotations.VisibleForTesting;
206import com.android.internal.logging.MetricsLogger;
207import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
208import com.android.internal.notification.SystemNotificationChannels;
209import com.android.internal.os.BackgroundThread;
210import com.android.internal.statusbar.IStatusBarService;
211import com.android.internal.util.DumpUtils;
212import com.android.internal.util.FastXmlSerializer;
213import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
214import com.android.internal.util.JournaledFile;
215import com.android.internal.util.Preconditions;
216import com.android.internal.util.XmlUtils;
217import com.android.internal.widget.LockPatternUtils;
218import com.android.server.LocalServices;
219import com.android.server.SystemServerInitThreadPool;
220import com.android.server.SystemService;
221import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
222import com.android.server.net.NetworkPolicyManagerInternal;
223import com.android.server.pm.UserRestrictionsUtils;
224
225import com.google.android.collect.Sets;
226
227import org.xmlpull.v1.XmlPullParser;
228import org.xmlpull.v1.XmlPullParserException;
229import org.xmlpull.v1.XmlSerializer;
230
231import java.io.File;
232import java.io.FileDescriptor;
233import java.io.FileInputStream;
234import java.io.FileNotFoundException;
235import java.io.FileOutputStream;
236import java.io.IOException;
237import java.io.PrintWriter;
238import java.lang.reflect.Constructor;
239import java.nio.charset.StandardCharsets;
240import java.text.DateFormat;
241import java.util.ArrayList;
242import java.util.Arrays;
243import java.util.Collection;
244import java.util.Collections;
245import java.util.Date;
246import java.util.HashMap;
247import java.util.List;
248import java.util.Map;
249import java.util.Map.Entry;
250import java.util.Objects;
251import java.util.Map.Entry;
252import java.util.Set;
253import java.util.concurrent.TimeUnit;
254import java.util.concurrent.atomic.AtomicBoolean;
255import java.util.function.Function;
256
257/**
258 * Implementation of the device policy APIs.
259 */
260public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
261
262    protected static final String LOG_TAG = "DevicePolicyManager";
263
264    private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
265
266    private static final String DEVICE_POLICIES_XML = "device_policies.xml";
267
268    private static final String TRANSFER_OWNERSHIP_PARAMETERS_XML =
269            "transfer-ownership-parameters.xml";
270
271    private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
272
273    private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
274
275    private static final String TAG_LOCK_TASK_FEATURES = "lock-task-features";
276
277    private static final String TAG_STATUS_BAR = "statusbar";
278
279    private static final String ATTR_DISABLED = "disabled";
280
281    private static final String ATTR_NAME = "name";
282
283    private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
284            "do-not-ask-credentials-on-boot";
285
286    private static final String TAG_AFFILIATION_ID = "affiliation-id";
287
288    private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval";
289
290    private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request";
291
292    private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval";
293
294    private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
295
296    private static final String TAG_CURRENT_INPUT_METHOD_SET = "current-ime-set";
297
298    private static final String TAG_OWNER_INSTALLED_CA_CERT = "owner-installed-ca-cert";
299
300    private static final String ATTR_ID = "id";
301
302    private static final String ATTR_VALUE = "value";
303
304    private static final String ATTR_ALIAS = "alias";
305
306    private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
307
308    private static final String TAG_PASSWORD_TOKEN_HANDLE = "password-token";
309
310    private static final String TAG_PASSWORD_VALIDITY = "password-validity";
311
312    private static final String TAG_PRINTING_ENABLED = "printing-enabled";
313
314    private static final int REQUEST_EXPIRE_PASSWORD = 5571;
315
316    private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);
317
318    private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
319
320    private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
321            = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
322
323    private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
324    private static final String ATTR_SETUP_COMPLETE = "setup-complete";
325    private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
326    private static final String ATTR_PERMISSION_POLICY = "permission-policy";
327    private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
328            "device-provisioning-config-applied";
329    private static final String ATTR_DEVICE_PAIRED = "device-paired";
330    private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
331    private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
332            = "application-restrictions-manager";
333
334    private static final String MANAGED_PROVISIONING_PKG = "com.android.managedprovisioning";
335
336    // Comprehensive list of delegations.
337    private static final String DELEGATIONS[] = {
338        DELEGATION_CERT_INSTALL,
339        DELEGATION_APP_RESTRICTIONS,
340        DELEGATION_BLOCK_UNINSTALL,
341        DELEGATION_ENABLE_SYSTEM_APP,
342        DELEGATION_KEEP_UNINSTALLED_PACKAGES,
343        DELEGATION_PACKAGE_ACCESS,
344        DELEGATION_PERMISSION_GRANT,
345        DELEGATION_INSTALL_EXISTING_PACKAGE,
346        DELEGATION_KEEP_UNINSTALLED_PACKAGES
347    };
348
349    /**
350     *  System property whose value is either "true" or "false", indicating whether
351     *  device owner is present.
352     */
353    private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
354
355    private static final int STATUS_BAR_DISABLE_MASK =
356            StatusBarManager.DISABLE_EXPAND |
357            StatusBarManager.DISABLE_NOTIFICATION_ICONS |
358            StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
359            StatusBarManager.DISABLE_SEARCH;
360
361    private static final int STATUS_BAR_DISABLE2_MASK =
362            StatusBarManager.DISABLE2_QUICK_SETTINGS;
363
364    private static final Set<String> SECURE_SETTINGS_WHITELIST;
365    private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
366    private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
367    private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
368    private static final Set<String> SYSTEM_SETTINGS_WHITELIST;
369    static {
370        SECURE_SETTINGS_WHITELIST = new ArraySet<>();
371        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
372        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
373        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
374
375        SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
376        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
377        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
378
379        GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
380        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
381        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
382        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
383        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
384        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
385        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
386        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
387        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
388
389        GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
390        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
391        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
392        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
393        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
394        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
395
396        SYSTEM_SETTINGS_WHITELIST = new ArraySet<>();
397        SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS);
398        SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE);
399        SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_OFF_TIMEOUT);
400    }
401
402    /**
403     * Keyguard features that when set on a profile affect the profile content or challenge only.
404     * These cannot be set on the managed profile's parent DPM instance
405     */
406    private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
407            DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
408
409    /** Keyguard features that are allowed to be set on a managed profile */
410    private static final int PROFILE_KEYGUARD_FEATURES =
411            PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
412
413    private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
414
415    /**
416     * Minimum timeout in milliseconds after which unlocking with weak auth times out,
417     * i.e. the user has to use a strong authentication method like password, PIN or pattern.
418     */
419    private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
420
421    /**
422     * Strings logged with {@link
423     * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}.
424     */
425    private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
426    private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
427
428    final Context mContext;
429    final Injector mInjector;
430    final IPackageManager mIPackageManager;
431    final UserManager mUserManager;
432    final UserManagerInternal mUserManagerInternal;
433    final UsageStatsManagerInternal mUsageStatsManagerInternal;
434    final TelephonyManager mTelephonyManager;
435    private final LockPatternUtils mLockPatternUtils;
436    private final DevicePolicyConstants mConstants;
437    private final DeviceAdminServiceController mDeviceAdminServiceController;
438    private final OverlayPackagesProvider mOverlayPackagesProvider;
439
440    /**
441     * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
442     * is requested for user u.
443     */
444    private final Set<Pair<String, Integer>> mPackagesToRemove =
445            new ArraySet<Pair<String, Integer>>();
446
447    final LocalService mLocalService;
448
449    // Stores and loads state on device and profile owners.
450    @VisibleForTesting
451    final Owners mOwners;
452
453    private final Binder mToken = new Binder();
454
455    /**
456     * Whether or not device admin feature is supported. If it isn't return defaults for all
457     * public methods.
458     */
459    boolean mHasFeature;
460
461    /**
462     * Whether or not this device is a watch.
463     */
464    boolean mIsWatch;
465
466    private final CertificateMonitor mCertificateMonitor;
467    private final SecurityLogMonitor mSecurityLogMonitor;
468    private NetworkLogger mNetworkLogger;
469
470    private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
471    private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
472
473    private SetupContentObserver mSetupContentObserver;
474
475    @VisibleForTesting
476    final TransferOwnershipMetadataManager mTransferOwnershipMetadataManager;
477
478    private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
479        @Override
480        public void run() {
481            if(mRemoteBugreportServiceIsActive.get()) {
482                onBugreportFailed();
483            }
484        }
485    };
486
487    /** Listens only if mHasFeature == true. */
488    private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
489
490        @Override
491        public void onReceive(Context context, Intent intent) {
492            if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
493                    && mRemoteBugreportServiceIsActive.get()) {
494                onBugreportFinished(intent);
495            }
496        }
497    };
498
499    /** Listens only if mHasFeature == true. */
500    private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
501
502        @Override
503        public void onReceive(Context context, Intent intent) {
504            String action = intent.getAction();
505            mInjector.getNotificationManager().cancel(LOG_TAG,
506                    RemoteBugreportUtils.NOTIFICATION_ID);
507            if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
508                onBugreportSharingAccepted();
509            } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
510                onBugreportSharingDeclined();
511            }
512            mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
513        }
514    };
515
516    public static final class Lifecycle extends SystemService {
517        private BaseIDevicePolicyManager mService;
518
519        public Lifecycle(Context context) {
520            super(context);
521            String dpmsClassName = context.getResources()
522                    .getString(R.string.config_deviceSpecificDevicePolicyManagerService);
523            if (TextUtils.isEmpty(dpmsClassName)) {
524                dpmsClassName = DevicePolicyManagerService.class.getName();
525            }
526            try {
527                Class serviceClass = Class.forName(dpmsClassName);
528                Constructor constructor = serviceClass.getConstructor(Context.class);
529                mService = (BaseIDevicePolicyManager) constructor.newInstance(context);
530            } catch (Exception e) {
531                throw new IllegalStateException(
532                    "Failed to instantiate DevicePolicyManagerService with class name: "
533                    + dpmsClassName, e);
534            }
535        }
536
537        @Override
538        public void onStart() {
539            publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
540        }
541
542        @Override
543        public void onBootPhase(int phase) {
544            mService.systemReady(phase);
545        }
546
547        @Override
548        public void onStartUser(int userHandle) {
549            mService.handleStartUser(userHandle);
550        }
551
552        @Override
553        public void onUnlockUser(int userHandle) {
554            mService.handleUnlockUser(userHandle);
555        }
556
557        @Override
558        public void onStopUser(int userHandle) {
559            mService.handleStopUser(userHandle);
560        }
561    }
562
563    public static class DevicePolicyData {
564        @NonNull PasswordMetrics mActivePasswordMetrics = new PasswordMetrics();
565        int mFailedPasswordAttempts = 0;
566        boolean mPasswordStateHasBeenSetSinceBoot = false;
567        boolean mPasswordValidAtLastCheckpoint = false;
568
569        int mUserHandle;
570        int mPasswordOwner = -1;
571        long mLastMaximumTimeToLock = -1;
572        boolean mUserSetupComplete = false;
573        boolean mPaired = false;
574        int mUserProvisioningState;
575        int mPermissionPolicy;
576
577        boolean mDeviceProvisioningConfigApplied = false;
578
579        final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
580        final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
581        final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
582
583        // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
584        final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
585
586        // This is the list of component allowed to start lock task mode.
587        List<String> mLockTaskPackages = new ArrayList<>();
588
589        // Bitfield of feature flags to be enabled during LockTask mode.
590        int mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
591
592        boolean mStatusBarDisabled = false;
593
594        ComponentName mRestrictionsProvider;
595
596        // Map of delegate package to delegation scopes
597        final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>();
598
599        boolean doNotAskCredentialsOnBoot = false;
600
601        Set<String> mAffiliationIds = new ArraySet<>();
602
603        long mLastSecurityLogRetrievalTime = -1;
604
605        long mLastBugReportRequestTime = -1;
606
607        long mLastNetworkLogsRetrievalTime = -1;
608
609        boolean mCurrentInputMethodSet = false;
610
611        // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
612        Set<String> mOwnerInstalledCaCerts = new ArraySet<>();
613
614        // Used for initialization of users created by createAndManageUser.
615        boolean mAdminBroadcastPending = false;
616        PersistableBundle mInitBundle = null;
617
618        long mPasswordTokenHandle = 0;
619
620        boolean mPrintingEnabled = true;
621
622        public DevicePolicyData(int userHandle) {
623            mUserHandle = userHandle;
624        }
625    }
626
627    final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
628
629    final Handler mHandler;
630    final Handler mBackgroundHandler;
631
632    /** Listens only if mHasFeature == true. */
633    final BroadcastReceiver mReceiver = new BroadcastReceiver() {
634        @Override
635        public void onReceive(Context context, Intent intent) {
636            final String action = intent.getAction();
637            final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
638                    getSendingUserId());
639
640            /*
641             * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
642             * however it's too early in the boot process to register with IIpConnectivityMetrics
643             * to listen for events.
644             */
645            if (Intent.ACTION_USER_STARTED.equals(action)
646                    && userHandle == mOwners.getDeviceOwnerUserId()) {
647                synchronized (DevicePolicyManagerService.this) {
648                    if (isNetworkLoggingEnabledInternalLocked()) {
649                        setNetworkLoggingActiveInternal(true);
650                    }
651                }
652            }
653            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
654                    && userHandle == mOwners.getDeviceOwnerUserId()
655                    && getDeviceOwnerRemoteBugreportUri() != null) {
656                IntentFilter filterConsent = new IntentFilter();
657                filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
658                filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
659                mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
660                mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
661                        RemoteBugreportUtils.NOTIFICATION_ID,
662                        RemoteBugreportUtils.buildNotification(mContext,
663                                DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
664                                UserHandle.ALL);
665            }
666            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
667                    || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
668                if (VERBOSE_LOG) {
669                    Slog.v(LOG_TAG, "Sending password expiration notifications for action "
670                            + action + " for user " + userHandle);
671                }
672                mHandler.post(new Runnable() {
673                    @Override
674                    public void run() {
675                        handlePasswordExpirationNotification(userHandle);
676                    }
677                });
678            }
679
680            if (Intent.ACTION_USER_ADDED.equals(action)) {
681                sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
682                synchronized (DevicePolicyManagerService.this) {
683                    // It might take a while for the user to become affiliated. Make security
684                    // and network logging unavailable in the meantime.
685                    maybePauseDeviceWideLoggingLocked();
686                }
687            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
688                sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
689                synchronized (DevicePolicyManagerService.this) {
690                    // Check whether the user is affiliated, *before* removing its data.
691                    boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
692                    removeUserData(userHandle);
693                    if (!isRemovedUserAffiliated) {
694                        // We discard the logs when unaffiliated users are deleted (so that the
695                        // device owner cannot retrieve data about that user after it's gone).
696                        discardDeviceWideLogsLocked();
697                        // Resume logging if all remaining users are affiliated.
698                        maybeResumeDeviceWideLoggingLocked();
699                    }
700                }
701            } else if (Intent.ACTION_USER_STARTED.equals(action)) {
702                sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle);
703                synchronized (DevicePolicyManagerService.this) {
704                    maybeSendAdminEnabledBroadcastLocked(userHandle);
705                    // Reset the policy data
706                    mUserData.remove(userHandle);
707                }
708                handlePackagesChanged(null /* check all admins */, userHandle);
709            } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
710                sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STOPPED, userHandle);
711            } else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
712                sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_SWITCHED, userHandle);
713            } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
714                synchronized (DevicePolicyManagerService.this) {
715                    maybeSendAdminEnabledBroadcastLocked(userHandle);
716                }
717            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
718                handlePackagesChanged(null /* check all admins */, userHandle);
719            } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
720                    || (Intent.ACTION_PACKAGE_ADDED.equals(action)
721                    && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
722                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
723            } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
724                    && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
725                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
726            } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
727                clearWipeProfileNotification();
728            }
729        }
730
731        private void sendDeviceOwnerUserCommand(String action, int userHandle) {
732            synchronized (DevicePolicyManagerService.this) {
733                ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
734                if (deviceOwner != null) {
735                    Bundle extras = new Bundle();
736                    extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
737                    sendAdminCommandLocked(deviceOwner, action, extras, /* result */ null,
738                            /* inForeground */ true);
739                }
740            }
741        }
742    };
743
744    protected static class RestrictionsListener implements UserRestrictionsListener {
745        private Context mContext;
746
747        public RestrictionsListener(Context context) {
748            mContext = context;
749        }
750
751        public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
752                Bundle prevRestrictions) {
753            final boolean newlyDisallowed =
754                    newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE);
755            final boolean previouslyDisallowed =
756                    prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE);
757            final boolean restrictionChanged = (newlyDisallowed != previouslyDisallowed);
758
759            if (restrictionChanged) {
760                // Notify ManagedProvisioning to update the built-in cross profile intent filters.
761                Intent intent = new Intent(
762                        DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
763                intent.setPackage(MANAGED_PROVISIONING_PKG);
764                intent.putExtra(Intent.EXTRA_USER_ID, userId);
765                intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
766                mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
767            }
768        }
769    }
770
771    static class ActiveAdmin {
772        private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
773        private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
774        private static final String TAG_DISABLE_CAMERA = "disable-camera";
775        private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
776        private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
777        private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
778                = "disable-bt-contacts-sharing";
779        private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
780        private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
781        private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
782        private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
783        private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled";
784        private static final String TAG_ACCOUNT_TYPE = "account-type";
785        private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
786                = "permitted-accessiblity-services";
787        private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
788        private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
789        private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
790        private static final String TAG_TRUST_AGENT_COMPONENT = "component";
791        private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
792        private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
793        private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
794        private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
795        private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
796        private static final String TAG_PERMITTED_IMES = "permitted-imes";
797        private static final String TAG_PERMITTED_NOTIFICATION_LISTENERS =
798                "permitted-notification-listeners";
799        private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
800        private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
801        private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
802        private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
803        private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
804        private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
805        private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
806        private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
807        private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
808        private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
809        private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
810        private static final String ATTR_VALUE = "value";
811        private static final String TAG_PASSWORD_BLACKLIST = "password-blacklist";
812        private static final String TAG_PASSWORD_QUALITY = "password-quality";
813        private static final String TAG_POLICIES = "policies";
814        private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
815                "cross-profile-widget-providers";
816        private static final String TAG_PROVIDER = "provider";
817        private static final String TAG_PACKAGE_LIST_ITEM  = "item";
818        private static final String TAG_KEEP_UNINSTALLED_PACKAGES  = "keep-uninstalled-packages";
819        private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
820        private static final String TAG_DEFAULT_ENABLED_USER_RESTRICTIONS =
821                "default-enabled-user-restrictions";
822        private static final String TAG_RESTRICTION = "restriction";
823        private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
824        private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
825        private static final String TAG_PARENT_ADMIN = "parent-admin";
826        private static final String TAG_ORGANIZATION_COLOR = "organization-color";
827        private static final String TAG_ORGANIZATION_NAME = "organization-name";
828        private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification";
829        private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications";
830        private static final String TAG_IS_LOGOUT_ENABLED = "is_logout_enabled";
831        private static final String TAG_MANDATORY_BACKUP_TRANSPORT = "mandatory_backup_transport";
832        private static final String TAG_START_USER_SESSION_MESSAGE = "start_user_session_message";
833        private static final String TAG_END_USER_SESSION_MESSAGE = "end_user_session_message";
834        private static final String TAG_METERED_DATA_DISABLED_PACKAGES
835                = "metered_data_disabled_packages";
836
837        DeviceAdminInfo info;
838
839
840        static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
841        int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
842
843        static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
844        static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
845        static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
846        static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
847        static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
848        static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
849        static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
850        @NonNull
851        PasswordMetrics minimumPasswordMetrics = new PasswordMetrics(
852                PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH,
853                DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE,
854                DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC,
855                DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER);
856
857        static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
858        long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
859
860        long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
861
862        static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
863        int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
864
865        static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
866        long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
867
868        static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
869        long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
870
871        static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
872
873        int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
874
875        boolean encryptionRequested = false;
876        boolean testOnlyAdmin = false;
877        boolean disableCamera = false;
878        boolean disableCallerId = false;
879        boolean disableContactsSearch = false;
880        boolean disableBluetoothContactSharing = true;
881        boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
882        boolean requireAutoTime = false; // Can only be set by a device owner.
883        boolean forceEphemeralUsers = false; // Can only be set by a device owner.
884        boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner.
885        boolean isLogoutEnabled = false; // Can only be set by a device owner.
886
887        // one notification after enabling + one more after reboots
888        static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 2;
889        int numNetworkLoggingNotifications = 0;
890        long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch
891
892        ActiveAdmin parentAdmin;
893        final boolean isParent;
894
895        static class TrustAgentInfo {
896            public PersistableBundle options;
897            TrustAgentInfo(PersistableBundle bundle) {
898                options = bundle;
899            }
900        }
901
902        // The list of packages which are not allowed to use metered data.
903        List<String> meteredDisabledPackages;
904
905        final Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
906
907        // The list of permitted accessibility services package namesas set by a profile
908        // or device owner. Null means all accessibility services are allowed, empty means
909        // none except system services are allowed.
910        List<String> permittedAccessiblityServices;
911
912        // The list of permitted input methods package names as set by a profile or device owner.
913        // Null means all input methods are allowed, empty means none except system imes are
914        // allowed.
915        List<String> permittedInputMethods;
916
917        // The list of packages allowed to use a NotificationListenerService to receive events for
918        // notifications from this user. Null means that all packages are allowed. Empty list means
919        // that only packages from the system are allowed.
920        List<String> permittedNotificationListeners;
921
922        // List of package names to keep cached.
923        List<String> keepUninstalledPackages;
924
925        // TODO: review implementation decisions with frameworks team
926        boolean specifiesGlobalProxy = false;
927        String globalProxySpec = null;
928        String globalProxyExclusionList = null;
929
930        ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
931
932        List<String> crossProfileWidgetProviders;
933
934        Bundle userRestrictions;
935
936        // User restrictions that have already been enabled by default for this admin (either when
937        // setting the device or profile owner, or during a system update if one of those "enabled
938        // by default" restrictions is newly added).
939        final Set<String> defaultEnabledRestrictionsAlreadySet = new ArraySet<>();
940
941        // Support text provided by the admin to display to the user.
942        CharSequence shortSupportMessage = null;
943        CharSequence longSupportMessage = null;
944
945        // Background color of confirm credentials screen. Default: teal.
946        static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
947        int organizationColor = DEF_ORGANIZATION_COLOR;
948
949        // Default title of confirm credentials screen
950        String organizationName = null;
951
952        // The blacklist data is stored in a file whose name is stored in the XML
953        String passwordBlacklistFile = null;
954
955        // The component name of the backup transport which has to be used if backups are mandatory
956        // or null if backups are not mandatory.
957        ComponentName mandatoryBackupTransport = null;
958
959        // Message for user switcher
960        String startUserSessionMessage = null;
961        String endUserSessionMessage = null;
962
963        ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
964            info = _info;
965            isParent = parent;
966        }
967
968        ActiveAdmin getParentActiveAdmin() {
969            Preconditions.checkState(!isParent);
970
971            if (parentAdmin == null) {
972                parentAdmin = new ActiveAdmin(info, /* parent */ true);
973            }
974            return parentAdmin;
975        }
976
977        boolean hasParentActiveAdmin() {
978            return parentAdmin != null;
979        }
980
981        int getUid() { return info.getActivityInfo().applicationInfo.uid; }
982
983        public UserHandle getUserHandle() {
984            return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
985        }
986
987        void writeToXml(XmlSerializer out)
988                throws IllegalArgumentException, IllegalStateException, IOException {
989            out.startTag(null, TAG_POLICIES);
990            info.writePoliciesToXml(out);
991            out.endTag(null, TAG_POLICIES);
992            if (minimumPasswordMetrics.quality != PASSWORD_QUALITY_UNSPECIFIED) {
993                out.startTag(null, TAG_PASSWORD_QUALITY);
994                out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality));
995                out.endTag(null, TAG_PASSWORD_QUALITY);
996                if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) {
997                    out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
998                    out.attribute(
999                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length));
1000                    out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
1001                }
1002                if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
1003                    out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
1004                    out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
1005                    out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
1006                }
1007                if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
1008                    out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
1009                    out.attribute(
1010                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase));
1011                    out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
1012                }
1013                if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
1014                    out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
1015                    out.attribute(
1016                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase));
1017                    out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
1018                }
1019                if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) {
1020                    out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
1021                    out.attribute(
1022                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters));
1023                    out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
1024                }
1025                if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
1026                    out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
1027                    out.attribute(
1028                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric));
1029                    out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
1030                }
1031                if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
1032                    out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
1033                    out.attribute(
1034                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols));
1035                    out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
1036                }
1037                if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
1038                    out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
1039                    out.attribute(
1040                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter));
1041                    out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
1042                }
1043            }
1044            if (passwordBlacklistFile != null) {
1045                out.startTag(null, TAG_PASSWORD_BLACKLIST);
1046                out.attribute(null, ATTR_VALUE, passwordBlacklistFile);
1047                out.endTag(null, TAG_PASSWORD_BLACKLIST);
1048            }
1049            if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
1050                out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
1051                out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
1052                out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
1053            }
1054            if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
1055                out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
1056                out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
1057                out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
1058            }
1059            if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
1060                out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
1061                out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
1062                out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
1063            }
1064            if (specifiesGlobalProxy) {
1065                out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
1066                out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
1067                out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
1068                if (globalProxySpec != null) {
1069                    out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
1070                    out.attribute(null, ATTR_VALUE, globalProxySpec);
1071                    out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
1072                }
1073                if (globalProxyExclusionList != null) {
1074                    out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
1075                    out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
1076                    out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
1077                }
1078            }
1079            if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
1080                out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
1081                out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
1082                out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
1083            }
1084            if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
1085                out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
1086                out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
1087                out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
1088            }
1089            if (encryptionRequested) {
1090                out.startTag(null, TAG_ENCRYPTION_REQUESTED);
1091                out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
1092                out.endTag(null, TAG_ENCRYPTION_REQUESTED);
1093            }
1094            if (testOnlyAdmin) {
1095                out.startTag(null, TAG_TEST_ONLY_ADMIN);
1096                out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
1097                out.endTag(null, TAG_TEST_ONLY_ADMIN);
1098            }
1099            if (disableCamera) {
1100                out.startTag(null, TAG_DISABLE_CAMERA);
1101                out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
1102                out.endTag(null, TAG_DISABLE_CAMERA);
1103            }
1104            if (disableCallerId) {
1105                out.startTag(null, TAG_DISABLE_CALLER_ID);
1106                out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
1107                out.endTag(null, TAG_DISABLE_CALLER_ID);
1108            }
1109            if (disableContactsSearch) {
1110                out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
1111                out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
1112                out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
1113            }
1114            if (!disableBluetoothContactSharing) {
1115                out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
1116                out.attribute(null, ATTR_VALUE,
1117                        Boolean.toString(disableBluetoothContactSharing));
1118                out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
1119            }
1120            if (disableScreenCapture) {
1121                out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
1122                out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
1123                out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
1124            }
1125            if (requireAutoTime) {
1126                out.startTag(null, TAG_REQUIRE_AUTO_TIME);
1127                out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
1128                out.endTag(null, TAG_REQUIRE_AUTO_TIME);
1129            }
1130            if (forceEphemeralUsers) {
1131                out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
1132                out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
1133                out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
1134            }
1135            if (isNetworkLoggingEnabled) {
1136                out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
1137                out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled));
1138                out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS,
1139                        Integer.toString(numNetworkLoggingNotifications));
1140                out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION,
1141                        Long.toString(lastNetworkLoggingNotificationTimeMs));
1142                out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
1143            }
1144            if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
1145                out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1146                out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
1147                out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1148            }
1149            if (!accountTypesWithManagementDisabled.isEmpty()) {
1150                out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
1151                writeAttributeValuesToXml(
1152                        out, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1153                out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
1154            }
1155            if (!trustAgentInfos.isEmpty()) {
1156                Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
1157                out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1158                for (Entry<String, TrustAgentInfo> entry : set) {
1159                    TrustAgentInfo trustAgentInfo = entry.getValue();
1160                    out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
1161                    out.attribute(null, ATTR_VALUE, entry.getKey());
1162                    if (trustAgentInfo.options != null) {
1163                        out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1164                        try {
1165                            trustAgentInfo.options.saveToXml(out);
1166                        } catch (XmlPullParserException e) {
1167                            Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
1168                        }
1169                        out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1170                    }
1171                    out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
1172                }
1173                out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1174            }
1175            if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
1176                out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1177                writeAttributeValuesToXml(out, TAG_PROVIDER, crossProfileWidgetProviders);
1178                out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1179            }
1180            writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
1181                    permittedAccessiblityServices);
1182            writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
1183            writePackageListToXml(out, TAG_PERMITTED_NOTIFICATION_LISTENERS,
1184                    permittedNotificationListeners);
1185            writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
1186            writePackageListToXml(out, TAG_METERED_DATA_DISABLED_PACKAGES, meteredDisabledPackages);
1187            if (hasUserRestrictions()) {
1188                UserRestrictionsUtils.writeRestrictions(
1189                        out, userRestrictions, TAG_USER_RESTRICTIONS);
1190            }
1191            if (!defaultEnabledRestrictionsAlreadySet.isEmpty()) {
1192                out.startTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1193                writeAttributeValuesToXml(
1194                        out, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1195                out.endTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1196            }
1197            if (!TextUtils.isEmpty(shortSupportMessage)) {
1198                out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1199                out.text(shortSupportMessage.toString());
1200                out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1201            }
1202            if (!TextUtils.isEmpty(longSupportMessage)) {
1203                out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
1204                out.text(longSupportMessage.toString());
1205                out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
1206            }
1207            if (parentAdmin != null) {
1208                out.startTag(null, TAG_PARENT_ADMIN);
1209                parentAdmin.writeToXml(out);
1210                out.endTag(null, TAG_PARENT_ADMIN);
1211            }
1212            if (organizationColor != DEF_ORGANIZATION_COLOR) {
1213                out.startTag(null, TAG_ORGANIZATION_COLOR);
1214                out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
1215                out.endTag(null, TAG_ORGANIZATION_COLOR);
1216            }
1217            if (organizationName != null) {
1218                out.startTag(null, TAG_ORGANIZATION_NAME);
1219                out.text(organizationName);
1220                out.endTag(null, TAG_ORGANIZATION_NAME);
1221            }
1222            if (isLogoutEnabled) {
1223                out.startTag(null, TAG_IS_LOGOUT_ENABLED);
1224                out.attribute(null, ATTR_VALUE, Boolean.toString(isLogoutEnabled));
1225                out.endTag(null, TAG_IS_LOGOUT_ENABLED);
1226            }
1227            if (mandatoryBackupTransport != null) {
1228                out.startTag(null, TAG_MANDATORY_BACKUP_TRANSPORT);
1229                out.attribute(null, ATTR_VALUE, mandatoryBackupTransport.flattenToString());
1230                out.endTag(null, TAG_MANDATORY_BACKUP_TRANSPORT);
1231            }
1232            if (startUserSessionMessage != null) {
1233                out.startTag(null, TAG_START_USER_SESSION_MESSAGE);
1234                out.text(startUserSessionMessage);
1235                out.endTag(null, TAG_START_USER_SESSION_MESSAGE);
1236            }
1237            if (endUserSessionMessage != null) {
1238                out.startTag(null, TAG_END_USER_SESSION_MESSAGE);
1239                out.text(endUserSessionMessage);
1240                out.endTag(null, TAG_END_USER_SESSION_MESSAGE);
1241            }
1242        }
1243
1244        void writePackageListToXml(XmlSerializer out, String outerTag,
1245                List<String> packageList)
1246                throws IllegalArgumentException, IllegalStateException, IOException {
1247            if (packageList == null) {
1248                return;
1249            }
1250
1251            out.startTag(null, outerTag);
1252            writeAttributeValuesToXml(out, TAG_PACKAGE_LIST_ITEM, packageList);
1253            out.endTag(null, outerTag);
1254        }
1255
1256        void writeAttributeValuesToXml(XmlSerializer out, String tag,
1257                @NonNull Collection<String> values) throws IOException {
1258            for (String value : values) {
1259                out.startTag(null, tag);
1260                out.attribute(null, ATTR_VALUE, value);
1261                out.endTag(null, tag);
1262            }
1263        }
1264
1265        void readFromXml(XmlPullParser parser)
1266                throws XmlPullParserException, IOException {
1267            int outerDepth = parser.getDepth();
1268            int type;
1269            while ((type=parser.next()) != END_DOCUMENT
1270                   && (type != END_TAG || parser.getDepth() > outerDepth)) {
1271                if (type == END_TAG || type == TEXT) {
1272                    continue;
1273                }
1274                String tag = parser.getName();
1275                if (TAG_POLICIES.equals(tag)) {
1276                    info.readPoliciesFromXml(parser);
1277                } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
1278                    minimumPasswordMetrics.quality = Integer.parseInt(
1279                            parser.getAttributeValue(null, ATTR_VALUE));
1280                } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
1281                    minimumPasswordMetrics.length = Integer.parseInt(
1282                            parser.getAttributeValue(null, ATTR_VALUE));
1283                } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
1284                    passwordHistoryLength = Integer.parseInt(
1285                            parser.getAttributeValue(null, ATTR_VALUE));
1286                } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
1287                    minimumPasswordMetrics.upperCase = Integer.parseInt(
1288                            parser.getAttributeValue(null, ATTR_VALUE));
1289                } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
1290                    minimumPasswordMetrics.lowerCase = Integer.parseInt(
1291                            parser.getAttributeValue(null, ATTR_VALUE));
1292                } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
1293                    minimumPasswordMetrics.letters = Integer.parseInt(
1294                            parser.getAttributeValue(null, ATTR_VALUE));
1295                } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
1296                    minimumPasswordMetrics.numeric = Integer.parseInt(
1297                            parser.getAttributeValue(null, ATTR_VALUE));
1298                } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
1299                    minimumPasswordMetrics.symbols = Integer.parseInt(
1300                            parser.getAttributeValue(null, ATTR_VALUE));
1301                } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
1302                    minimumPasswordMetrics.nonLetter = Integer.parseInt(
1303                            parser.getAttributeValue(null, ATTR_VALUE));
1304                } else if (TAG_PASSWORD_BLACKLIST.equals(tag)) {
1305                    passwordBlacklistFile = parser.getAttributeValue(null, ATTR_VALUE);
1306                }else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
1307                    maximumTimeToUnlock = Long.parseLong(
1308                            parser.getAttributeValue(null, ATTR_VALUE));
1309                } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
1310                    strongAuthUnlockTimeout = Long.parseLong(
1311                            parser.getAttributeValue(null, ATTR_VALUE));
1312                } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
1313                    maximumFailedPasswordsForWipe = Integer.parseInt(
1314                            parser.getAttributeValue(null, ATTR_VALUE));
1315                } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
1316                    specifiesGlobalProxy = Boolean.parseBoolean(
1317                            parser.getAttributeValue(null, ATTR_VALUE));
1318                } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1319                    globalProxySpec =
1320                        parser.getAttributeValue(null, ATTR_VALUE);
1321                } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1322                    globalProxyExclusionList =
1323                        parser.getAttributeValue(null, ATTR_VALUE);
1324                } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1325                    passwordExpirationTimeout = Long.parseLong(
1326                            parser.getAttributeValue(null, ATTR_VALUE));
1327                } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1328                    passwordExpirationDate = Long.parseLong(
1329                            parser.getAttributeValue(null, ATTR_VALUE));
1330                } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1331                    encryptionRequested = Boolean.parseBoolean(
1332                            parser.getAttributeValue(null, ATTR_VALUE));
1333                } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1334                    testOnlyAdmin = Boolean.parseBoolean(
1335                            parser.getAttributeValue(null, ATTR_VALUE));
1336                } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1337                    disableCamera = Boolean.parseBoolean(
1338                            parser.getAttributeValue(null, ATTR_VALUE));
1339                } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1340                    disableCallerId = Boolean.parseBoolean(
1341                            parser.getAttributeValue(null, ATTR_VALUE));
1342                } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1343                    disableContactsSearch = Boolean.parseBoolean(
1344                            parser.getAttributeValue(null, ATTR_VALUE));
1345                } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1346                    disableBluetoothContactSharing = Boolean.parseBoolean(parser
1347                            .getAttributeValue(null, ATTR_VALUE));
1348                } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1349                    disableScreenCapture = Boolean.parseBoolean(
1350                            parser.getAttributeValue(null, ATTR_VALUE));
1351                } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1352                    requireAutoTime = Boolean.parseBoolean(
1353                            parser.getAttributeValue(null, ATTR_VALUE));
1354                } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1355                    forceEphemeralUsers = Boolean.parseBoolean(
1356                            parser.getAttributeValue(null, ATTR_VALUE));
1357                } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) {
1358                    isNetworkLoggingEnabled = Boolean.parseBoolean(
1359                            parser.getAttributeValue(null, ATTR_VALUE));
1360                    lastNetworkLoggingNotificationTimeMs = Long.parseLong(
1361                            parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION));
1362                    numNetworkLoggingNotifications = Integer.parseInt(
1363                            parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS));
1364                } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1365                    disabledKeyguardFeatures = Integer.parseInt(
1366                            parser.getAttributeValue(null, ATTR_VALUE));
1367                } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1368                    readAttributeValues(
1369                            parser, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1370                } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1371                    trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1372                } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1373                    crossProfileWidgetProviders = new ArrayList<>();
1374                    readAttributeValues(parser, TAG_PROVIDER, crossProfileWidgetProviders);
1375                } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1376                    permittedAccessiblityServices = readPackageList(parser, tag);
1377                } else if (TAG_PERMITTED_IMES.equals(tag)) {
1378                    permittedInputMethods = readPackageList(parser, tag);
1379                } else if (TAG_PERMITTED_NOTIFICATION_LISTENERS.equals(tag)) {
1380                    permittedNotificationListeners = readPackageList(parser, tag);
1381                } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1382                    keepUninstalledPackages = readPackageList(parser, tag);
1383                } else if (TAG_METERED_DATA_DISABLED_PACKAGES.equals(tag)) {
1384                    meteredDisabledPackages = readPackageList(parser, tag);
1385                } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1386                    userRestrictions = UserRestrictionsUtils.readRestrictions(parser);
1387                } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) {
1388                    readAttributeValues(
1389                            parser, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1390                } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1391                    type = parser.next();
1392                    if (type == XmlPullParser.TEXT) {
1393                        shortSupportMessage = parser.getText();
1394                    } else {
1395                        Log.w(LOG_TAG, "Missing text when loading short support message");
1396                    }
1397                } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1398                    type = parser.next();
1399                    if (type == XmlPullParser.TEXT) {
1400                        longSupportMessage = parser.getText();
1401                    } else {
1402                        Log.w(LOG_TAG, "Missing text when loading long support message");
1403                    }
1404                } else if (TAG_PARENT_ADMIN.equals(tag)) {
1405                    Preconditions.checkState(!isParent);
1406
1407                    parentAdmin = new ActiveAdmin(info, /* parent */ true);
1408                    parentAdmin.readFromXml(parser);
1409                } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1410                    organizationColor = Integer.parseInt(
1411                            parser.getAttributeValue(null, ATTR_VALUE));
1412                } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1413                    type = parser.next();
1414                    if (type == XmlPullParser.TEXT) {
1415                        organizationName = parser.getText();
1416                    } else {
1417                        Log.w(LOG_TAG, "Missing text when loading organization name");
1418                    }
1419                } else if (TAG_IS_LOGOUT_ENABLED.equals(tag)) {
1420                    isLogoutEnabled = Boolean.parseBoolean(
1421                            parser.getAttributeValue(null, ATTR_VALUE));
1422                } else if (TAG_MANDATORY_BACKUP_TRANSPORT.equals(tag)) {
1423                    mandatoryBackupTransport = ComponentName.unflattenFromString(
1424                            parser.getAttributeValue(null, ATTR_VALUE));
1425                } else if (TAG_START_USER_SESSION_MESSAGE.equals(tag)) {
1426                    type = parser.next();
1427                    if (type == XmlPullParser.TEXT) {
1428                        startUserSessionMessage = parser.getText();
1429                    } else {
1430                        Log.w(LOG_TAG, "Missing text when loading start session message");
1431                    }
1432                } else if (TAG_END_USER_SESSION_MESSAGE.equals(tag)) {
1433                    type = parser.next();
1434                    if (type == XmlPullParser.TEXT) {
1435                        endUserSessionMessage = parser.getText();
1436                    } else {
1437                        Log.w(LOG_TAG, "Missing text when loading end session message");
1438                    }
1439                } else {
1440                    Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1441                    XmlUtils.skipCurrentTag(parser);
1442                }
1443            }
1444        }
1445
1446        private List<String> readPackageList(XmlPullParser parser,
1447                String tag) throws XmlPullParserException, IOException {
1448            List<String> result = new ArrayList<String>();
1449            int outerDepth = parser.getDepth();
1450            int outerType;
1451            while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1452                    && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1453                if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1454                    continue;
1455                }
1456                String outerTag = parser.getName();
1457                if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1458                    String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1459                    if (packageName != null) {
1460                        result.add(packageName);
1461                    } else {
1462                        Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1463                    }
1464                } else {
1465                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
1466                }
1467            }
1468            return result;
1469        }
1470
1471        private void readAttributeValues(
1472                XmlPullParser parser, String tag, Collection<String> result)
1473                throws XmlPullParserException, IOException {
1474            result.clear();
1475            int outerDepthDAM = parser.getDepth();
1476            int typeDAM;
1477            while ((typeDAM=parser.next()) != END_DOCUMENT
1478                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1479                if (typeDAM == END_TAG || typeDAM == TEXT) {
1480                    continue;
1481                }
1482                String tagDAM = parser.getName();
1483                if (tag.equals(tagDAM)) {
1484                    result.add(parser.getAttributeValue(null, ATTR_VALUE));
1485                } else {
1486                    Slog.e(LOG_TAG, "Expected tag " + tag +  " but found " + tagDAM);
1487                }
1488            }
1489        }
1490
1491        private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1492                XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1493            int outerDepthDAM = parser.getDepth();
1494            int typeDAM;
1495            final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1496            while ((typeDAM=parser.next()) != END_DOCUMENT
1497                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1498                if (typeDAM == END_TAG || typeDAM == TEXT) {
1499                    continue;
1500                }
1501                String tagDAM = parser.getName();
1502                if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1503                    final String component = parser.getAttributeValue(null, ATTR_VALUE);
1504                    final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1505                    result.put(component, trustAgentInfo);
1506                } else {
1507                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1508                }
1509            }
1510            return result;
1511        }
1512
1513        private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1514                throws XmlPullParserException, IOException  {
1515            int outerDepthDAM = parser.getDepth();
1516            int typeDAM;
1517            TrustAgentInfo result = new TrustAgentInfo(null);
1518            while ((typeDAM=parser.next()) != END_DOCUMENT
1519                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1520                if (typeDAM == END_TAG || typeDAM == TEXT) {
1521                    continue;
1522                }
1523                String tagDAM = parser.getName();
1524                if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1525                    result.options = PersistableBundle.restoreFromXml(parser);
1526                } else {
1527                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1528                }
1529            }
1530            return result;
1531        }
1532
1533        boolean hasUserRestrictions() {
1534            return userRestrictions != null && userRestrictions.size() > 0;
1535        }
1536
1537        Bundle ensureUserRestrictions() {
1538            if (userRestrictions == null) {
1539                userRestrictions = new Bundle();
1540            }
1541            return userRestrictions;
1542        }
1543
1544        public void transfer(DeviceAdminInfo deviceAdminInfo) {
1545            if (hasParentActiveAdmin()) {
1546                parentAdmin.info = deviceAdminInfo;
1547            }
1548            info = deviceAdminInfo;
1549        }
1550
1551        void dump(String prefix, PrintWriter pw) {
1552            pw.print(prefix); pw.print("uid="); pw.println(getUid());
1553            pw.print(prefix); pw.print("testOnlyAdmin=");
1554            pw.println(testOnlyAdmin);
1555            pw.print(prefix); pw.println("policies:");
1556            ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1557            if (pols != null) {
1558                for (int i=0; i<pols.size(); i++) {
1559                    pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
1560                }
1561            }
1562            pw.print(prefix); pw.print("passwordQuality=0x");
1563                    pw.println(Integer.toHexString(minimumPasswordMetrics.quality));
1564            pw.print(prefix); pw.print("minimumPasswordLength=");
1565                    pw.println(minimumPasswordMetrics.length);
1566            pw.print(prefix); pw.print("passwordHistoryLength=");
1567                    pw.println(passwordHistoryLength);
1568            pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1569                    pw.println(minimumPasswordMetrics.upperCase);
1570            pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1571                    pw.println(minimumPasswordMetrics.lowerCase);
1572            pw.print(prefix); pw.print("minimumPasswordLetters=");
1573                    pw.println(minimumPasswordMetrics.letters);
1574            pw.print(prefix); pw.print("minimumPasswordNumeric=");
1575                    pw.println(minimumPasswordMetrics.numeric);
1576            pw.print(prefix); pw.print("minimumPasswordSymbols=");
1577                    pw.println(minimumPasswordMetrics.symbols);
1578            pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1579                    pw.println(minimumPasswordMetrics.nonLetter);
1580            pw.print(prefix); pw.print("passwordBlacklist=");
1581                    pw.println(passwordBlacklistFile != null);
1582            pw.print(prefix); pw.print("maximumTimeToUnlock=");
1583                    pw.println(maximumTimeToUnlock);
1584            pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1585                    pw.println(strongAuthUnlockTimeout);
1586            pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1587                    pw.println(maximumFailedPasswordsForWipe);
1588            pw.print(prefix); pw.print("specifiesGlobalProxy=");
1589                    pw.println(specifiesGlobalProxy);
1590            pw.print(prefix); pw.print("passwordExpirationTimeout=");
1591                    pw.println(passwordExpirationTimeout);
1592            pw.print(prefix); pw.print("passwordExpirationDate=");
1593                    pw.println(passwordExpirationDate);
1594            if (globalProxySpec != null) {
1595                pw.print(prefix); pw.print("globalProxySpec=");
1596                        pw.println(globalProxySpec);
1597            }
1598            if (globalProxyExclusionList != null) {
1599                pw.print(prefix); pw.print("globalProxyEclusionList=");
1600                        pw.println(globalProxyExclusionList);
1601            }
1602            pw.print(prefix); pw.print("encryptionRequested=");
1603                    pw.println(encryptionRequested);
1604            pw.print(prefix); pw.print("disableCamera=");
1605                    pw.println(disableCamera);
1606            pw.print(prefix); pw.print("disableCallerId=");
1607                    pw.println(disableCallerId);
1608            pw.print(prefix); pw.print("disableContactsSearch=");
1609                    pw.println(disableContactsSearch);
1610            pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1611                    pw.println(disableBluetoothContactSharing);
1612            pw.print(prefix); pw.print("disableScreenCapture=");
1613                    pw.println(disableScreenCapture);
1614            pw.print(prefix); pw.print("requireAutoTime=");
1615                    pw.println(requireAutoTime);
1616            pw.print(prefix); pw.print("forceEphemeralUsers=");
1617                    pw.println(forceEphemeralUsers);
1618            pw.print(prefix); pw.print("isNetworkLoggingEnabled=");
1619                    pw.println(isNetworkLoggingEnabled);
1620            pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1621                    pw.println(disabledKeyguardFeatures);
1622            pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1623                    pw.println(crossProfileWidgetProviders);
1624            if (permittedAccessiblityServices != null) {
1625                pw.print(prefix); pw.print("permittedAccessibilityServices=");
1626                    pw.println(permittedAccessiblityServices);
1627            }
1628            if (permittedInputMethods != null) {
1629                pw.print(prefix); pw.print("permittedInputMethods=");
1630                    pw.println(permittedInputMethods);
1631            }
1632            if (permittedNotificationListeners != null) {
1633                pw.print(prefix); pw.print("permittedNotificationListeners=");
1634                pw.println(permittedNotificationListeners);
1635            }
1636            if (keepUninstalledPackages != null) {
1637                pw.print(prefix); pw.print("keepUninstalledPackages=");
1638                    pw.println(keepUninstalledPackages);
1639            }
1640            pw.print(prefix); pw.print("organizationColor=");
1641                    pw.println(organizationColor);
1642            if (organizationName != null) {
1643                pw.print(prefix); pw.print("organizationName=");
1644                    pw.println(organizationName);
1645            }
1646            pw.print(prefix); pw.println("userRestrictions:");
1647            UserRestrictionsUtils.dumpRestrictions(pw, prefix + "  ", userRestrictions);
1648            pw.print(prefix); pw.print("defaultEnabledRestrictionsAlreadySet=");
1649                    pw.println(defaultEnabledRestrictionsAlreadySet);
1650            pw.print(prefix); pw.print("isParent=");
1651                    pw.println(isParent);
1652            if (parentAdmin != null) {
1653                pw.print(prefix);  pw.println("parentAdmin:");
1654                parentAdmin.dump(prefix + "  ", pw);
1655            }
1656        }
1657    }
1658
1659    private void handlePackagesChanged(@Nullable String packageName, int userHandle) {
1660        boolean removedAdmin = false;
1661        if (VERBOSE_LOG) {
1662            Slog.d(LOG_TAG, "Handling package changes package " + packageName
1663                    + " for user " + userHandle);
1664        }
1665        DevicePolicyData policy = getUserData(userHandle);
1666        synchronized (this) {
1667            for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1668                ActiveAdmin aa = policy.mAdminList.get(i);
1669                try {
1670                    // If we're checking all packages or if the specific one we're checking matches,
1671                    // then check if the package and receiver still exist.
1672                    final String adminPackage = aa.info.getPackageName();
1673                    if (packageName == null || packageName.equals(adminPackage)) {
1674                        if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1675                                || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1676                                PackageManager.MATCH_DIRECT_BOOT_AWARE
1677                                        | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1678                                userHandle) == null) {
1679                            removedAdmin = true;
1680                            policy.mAdminList.remove(i);
1681                            policy.mAdminMap.remove(aa.info.getComponent());
1682                            pushActiveAdminPackagesLocked(userHandle);
1683                            pushMeteredDisabledPackagesLocked(userHandle);
1684                        }
1685                    }
1686                } catch (RemoteException re) {
1687                    // Shouldn't happen.
1688                }
1689            }
1690            if (removedAdmin) {
1691                validatePasswordOwnerLocked(policy);
1692            }
1693
1694            boolean removedDelegate = false;
1695
1696            // Check if a delegate was removed.
1697            for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
1698                final String delegatePackage = policy.mDelegationMap.keyAt(i);
1699                if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
1700                    policy.mDelegationMap.removeAt(i);
1701                    removedDelegate = true;
1702                }
1703            }
1704
1705            // If it's an owner package, we may need to refresh the bound connection.
1706            final ComponentName owner = getOwnerComponent(userHandle);
1707            if ((packageName != null) && (owner != null)
1708                    && (owner.getPackageName().equals(packageName))) {
1709                startOwnerService(userHandle, "package-broadcast");
1710            }
1711
1712            // Persist updates if the removed package was an admin or delegate.
1713            if (removedAdmin || removedDelegate) {
1714                saveSettingsLocked(policy.mUserHandle);
1715            }
1716        }
1717        if (removedAdmin) {
1718            // The removed admin might have disabled camera, so update user restrictions.
1719            pushUserRestrictions(userHandle);
1720        }
1721    }
1722
1723    private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1724        try {
1725            return targetPackage != null
1726                    && (changedPackage == null || changedPackage.equals(targetPackage))
1727                    && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1728        } catch (RemoteException e) {
1729            // Shouldn't happen
1730        }
1731
1732        return false;
1733    }
1734
1735    /**
1736     * Unit test will subclass it to inject mocks.
1737     */
1738    @VisibleForTesting
1739    static class Injector {
1740
1741        public final Context mContext;
1742
1743        Injector(Context context) {
1744            mContext = context;
1745        }
1746
1747        public boolean hasFeature() {
1748            return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1749        }
1750
1751        Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
1752            final String packageName = mContext.getPackageName();
1753            return mContext.createPackageContextAsUser(packageName, 0, user);
1754        }
1755
1756        Resources getResources() {
1757            return mContext.getResources();
1758        }
1759
1760        Owners newOwners() {
1761            return new Owners(getUserManager(), getUserManagerInternal(),
1762                    getPackageManagerInternal());
1763        }
1764
1765        UserManager getUserManager() {
1766            return UserManager.get(mContext);
1767        }
1768
1769        UserManagerInternal getUserManagerInternal() {
1770            return LocalServices.getService(UserManagerInternal.class);
1771        }
1772
1773        PackageManagerInternal getPackageManagerInternal() {
1774            return LocalServices.getService(PackageManagerInternal.class);
1775        }
1776
1777        UsageStatsManagerInternal getUsageStatsManagerInternal() {
1778            return LocalServices.getService(UsageStatsManagerInternal.class);
1779        }
1780
1781        NetworkPolicyManagerInternal getNetworkPolicyManagerInternal() {
1782            return LocalServices.getService(NetworkPolicyManagerInternal.class);
1783        }
1784
1785        NotificationManager getNotificationManager() {
1786            return mContext.getSystemService(NotificationManager.class);
1787        }
1788
1789        IIpConnectivityMetrics getIIpConnectivityMetrics() {
1790            return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1791                ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1792        }
1793
1794        PackageManager getPackageManager() {
1795            return mContext.getPackageManager();
1796        }
1797
1798        PowerManagerInternal getPowerManagerInternal() {
1799            return LocalServices.getService(PowerManagerInternal.class);
1800        }
1801
1802        TelephonyManager getTelephonyManager() {
1803            return TelephonyManager.from(mContext);
1804        }
1805
1806        TrustManager getTrustManager() {
1807            return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1808        }
1809
1810        AlarmManager getAlarmManager() {
1811            return (AlarmManager) mContext.getSystemService(AlarmManager.class);
1812        }
1813
1814        IWindowManager getIWindowManager() {
1815            return IWindowManager.Stub
1816                    .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1817        }
1818
1819        IActivityManager getIActivityManager() {
1820            return ActivityManager.getService();
1821        }
1822
1823        ActivityManagerInternal getActivityManagerInternal() {
1824            return LocalServices.getService(ActivityManagerInternal.class);
1825        }
1826
1827        IPackageManager getIPackageManager() {
1828            return AppGlobals.getPackageManager();
1829        }
1830
1831        IBackupManager getIBackupManager() {
1832            return IBackupManager.Stub.asInterface(
1833                    ServiceManager.getService(Context.BACKUP_SERVICE));
1834        }
1835
1836        IAudioService getIAudioService() {
1837            return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1838        }
1839
1840        boolean isBuildDebuggable() {
1841            return Build.IS_DEBUGGABLE;
1842        }
1843
1844        LockPatternUtils newLockPatternUtils() {
1845            return new LockPatternUtils(mContext);
1846        }
1847
1848        PasswordBlacklist newPasswordBlacklist(File file) {
1849            return new PasswordBlacklist(file);
1850        }
1851
1852        boolean storageManagerIsFileBasedEncryptionEnabled() {
1853            return StorageManager.isFileEncryptedNativeOnly();
1854        }
1855
1856        boolean storageManagerIsNonDefaultBlockEncrypted() {
1857            long identity = Binder.clearCallingIdentity();
1858            try {
1859                return StorageManager.isNonDefaultBlockEncrypted();
1860            } finally {
1861                Binder.restoreCallingIdentity(identity);
1862            }
1863        }
1864
1865        boolean storageManagerIsEncrypted() {
1866            return StorageManager.isEncrypted();
1867        }
1868
1869        boolean storageManagerIsEncryptable() {
1870            return StorageManager.isEncryptable();
1871        }
1872
1873        Looper getMyLooper() {
1874            return Looper.myLooper();
1875        }
1876
1877        WifiManager getWifiManager() {
1878            return mContext.getSystemService(WifiManager.class);
1879        }
1880
1881        long binderClearCallingIdentity() {
1882            return Binder.clearCallingIdentity();
1883        }
1884
1885        void binderRestoreCallingIdentity(long token) {
1886            Binder.restoreCallingIdentity(token);
1887        }
1888
1889        int binderGetCallingUid() {
1890            return Binder.getCallingUid();
1891        }
1892
1893        int binderGetCallingPid() {
1894            return Binder.getCallingPid();
1895        }
1896
1897        UserHandle binderGetCallingUserHandle() {
1898            return Binder.getCallingUserHandle();
1899        }
1900
1901        boolean binderIsCallingUidMyUid() {
1902            return getCallingUid() == Process.myUid();
1903        }
1904
1905        void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) {
1906             Binder.withCleanCallingIdentity(action);
1907        }
1908
1909        final int userHandleGetCallingUserId() {
1910            return UserHandle.getUserId(binderGetCallingUid());
1911        }
1912
1913        File environmentGetUserSystemDirectory(int userId) {
1914            return Environment.getUserSystemDirectory(userId);
1915        }
1916
1917        void powerManagerGoToSleep(long time, int reason, int flags) {
1918            mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1919        }
1920
1921        void powerManagerReboot(String reason) {
1922            mContext.getSystemService(PowerManager.class).reboot(reason);
1923        }
1924
1925        void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force,
1926                boolean wipeEuicc) throws IOException {
1927            RecoverySystem.rebootWipeUserData(mContext, shutdown, reason, force, wipeEuicc);
1928        }
1929
1930        boolean systemPropertiesGetBoolean(String key, boolean def) {
1931            return SystemProperties.getBoolean(key, def);
1932        }
1933
1934        long systemPropertiesGetLong(String key, long def) {
1935            return SystemProperties.getLong(key, def);
1936        }
1937
1938        String systemPropertiesGet(String key, String def) {
1939            return SystemProperties.get(key, def);
1940        }
1941
1942        String systemPropertiesGet(String key) {
1943            return SystemProperties.get(key);
1944        }
1945
1946        void systemPropertiesSet(String key, String value) {
1947            SystemProperties.set(key, value);
1948        }
1949
1950        boolean userManagerIsSplitSystemUser() {
1951            return UserManager.isSplitSystemUser();
1952        }
1953
1954        String getDevicePolicyFilePathForSystemUser() {
1955            return "/data/system/";
1956        }
1957
1958        PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode,
1959                @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
1960            return PendingIntent.getActivityAsUser(
1961                    context, requestCode, intent, flags, options, user);
1962        }
1963
1964        void registerContentObserver(Uri uri, boolean notifyForDescendents,
1965                ContentObserver observer, int userHandle) {
1966            mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1967                    observer, userHandle);
1968        }
1969
1970        int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1971            return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1972                    name, def, userHandle);
1973        }
1974
1975        String settingsSecureGetStringForUser(String name, int userHandle) {
1976            return Settings.Secure.getStringForUser(mContext.getContentResolver(), name,
1977                    userHandle);
1978        }
1979
1980        void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1981            Settings.Secure.putIntForUser(mContext.getContentResolver(),
1982                    name, value, userHandle);
1983        }
1984
1985        void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1986            Settings.Secure.putStringForUser(mContext.getContentResolver(),
1987                    name, value, userHandle);
1988        }
1989
1990        void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1991            Settings.Global.putStringForUser(mContext.getContentResolver(),
1992                    name, value, userHandle);
1993        }
1994
1995        void settingsSecurePutInt(String name, int value) {
1996            Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1997        }
1998
1999        int settingsGlobalGetInt(String name, int def) {
2000            return Settings.Global.getInt(mContext.getContentResolver(), name, def);
2001        }
2002
2003        String settingsGlobalGetString(String name) {
2004            return Settings.Global.getString(mContext.getContentResolver(), name);
2005        }
2006
2007        void settingsGlobalPutInt(String name, int value) {
2008            Settings.Global.putInt(mContext.getContentResolver(), name, value);
2009        }
2010
2011        void settingsSecurePutString(String name, String value) {
2012            Settings.Secure.putString(mContext.getContentResolver(), name, value);
2013        }
2014
2015        void settingsGlobalPutString(String name, String value) {
2016            Settings.Global.putString(mContext.getContentResolver(), name, value);
2017        }
2018
2019        void settingsSystemPutString(String name, String value) {
2020            Settings.System.putString(mContext.getContentResolver(), name, value);
2021        }
2022
2023        void securityLogSetLoggingEnabledProperty(boolean enabled) {
2024            SecurityLog.setLoggingEnabledProperty(enabled);
2025        }
2026
2027        boolean securityLogGetLoggingEnabledProperty() {
2028            return SecurityLog.getLoggingEnabledProperty();
2029        }
2030
2031        boolean securityLogIsLoggingEnabled() {
2032            return SecurityLog.isLoggingEnabled();
2033        }
2034
2035        KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException {
2036            return KeyChain.bindAsUser(mContext, user);
2037        }
2038
2039        void postOnSystemServerInitThreadPool(Runnable runnable) {
2040            SystemServerInitThreadPool.get().submit(runnable, LOG_TAG);
2041        }
2042
2043        public TransferOwnershipMetadataManager newTransferOwnershipMetadataManager() {
2044            return new TransferOwnershipMetadataManager();
2045        }
2046    }
2047
2048    /**
2049     * Instantiates the service.
2050     */
2051    public DevicePolicyManagerService(Context context) {
2052        this(new Injector(context));
2053    }
2054
2055    @VisibleForTesting
2056    DevicePolicyManagerService(Injector injector) {
2057        mInjector = injector;
2058        mContext = Preconditions.checkNotNull(injector.mContext);
2059        mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
2060        mConstants = DevicePolicyConstants.loadFromString(
2061                mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS));
2062
2063        mOwners = Preconditions.checkNotNull(injector.newOwners());
2064
2065        mUserManager = Preconditions.checkNotNull(injector.getUserManager());
2066        mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
2067        mUsageStatsManagerInternal = Preconditions.checkNotNull(
2068                injector.getUsageStatsManagerInternal());
2069        mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
2070        mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
2071
2072        mLocalService = new LocalService();
2073        mLockPatternUtils = injector.newLockPatternUtils();
2074
2075        // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false?
2076        mSecurityLogMonitor = new SecurityLogMonitor(this);
2077
2078        mHasFeature = mInjector.hasFeature();
2079        mIsWatch = mInjector.getPackageManager()
2080                .hasSystemFeature(PackageManager.FEATURE_WATCH);
2081        mBackgroundHandler = BackgroundThread.getHandler();
2082
2083        // Needed when mHasFeature == false, because it controls the certificate warning text.
2084        mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler);
2085
2086        mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants);
2087
2088        mOverlayPackagesProvider = new OverlayPackagesProvider(mContext);
2089
2090        mTransferOwnershipMetadataManager = mInjector.newTransferOwnershipMetadataManager();
2091
2092        if (!mHasFeature) {
2093            // Skip the rest of the initialization
2094            return;
2095        }
2096
2097        IntentFilter filter = new IntentFilter();
2098        filter.addAction(Intent.ACTION_BOOT_COMPLETED);
2099        filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
2100        filter.addAction(Intent.ACTION_USER_ADDED);
2101        filter.addAction(Intent.ACTION_USER_REMOVED);
2102        filter.addAction(Intent.ACTION_USER_STARTED);
2103        filter.addAction(Intent.ACTION_USER_STOPPED);
2104        filter.addAction(Intent.ACTION_USER_SWITCHED);
2105        filter.addAction(Intent.ACTION_USER_UNLOCKED);
2106        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2107        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2108        filter = new IntentFilter();
2109        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
2110        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2111        filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
2112        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
2113        filter.addDataScheme("package");
2114        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2115        filter = new IntentFilter();
2116        filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
2117        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2118
2119        LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
2120
2121        mSetupContentObserver = new SetupContentObserver(mHandler);
2122
2123        mUserManagerInternal.addUserRestrictionsListener(new RestrictionsListener(mContext));
2124    }
2125
2126    /**
2127     * Creates and loads the policy data from xml.
2128     * @param userHandle the user for whom to load the policy data
2129     * @return
2130     */
2131    @NonNull
2132    DevicePolicyData getUserData(int userHandle) {
2133        synchronized (this) {
2134            DevicePolicyData policy = mUserData.get(userHandle);
2135            if (policy == null) {
2136                policy = new DevicePolicyData(userHandle);
2137                mUserData.append(userHandle, policy);
2138                loadSettingsLocked(policy, userHandle);
2139            }
2140            return policy;
2141        }
2142    }
2143
2144    /**
2145     * Creates and loads the policy data from xml for data that is shared between
2146     * various profiles of a user. In contrast to {@link #getUserData(int)}
2147     * it allows access to data of users other than the calling user.
2148     *
2149     * This function should only be used for shared data, e.g. everything regarding
2150     * passwords and should be removed once multiple screen locks are present.
2151     * @param userHandle the user for whom to load the policy data
2152     * @return
2153     */
2154    DevicePolicyData getUserDataUnchecked(int userHandle) {
2155        long ident = mInjector.binderClearCallingIdentity();
2156        try {
2157            return getUserData(userHandle);
2158        } finally {
2159            mInjector.binderRestoreCallingIdentity(ident);
2160        }
2161    }
2162
2163    void removeUserData(int userHandle) {
2164        synchronized (this) {
2165            if (userHandle == UserHandle.USER_SYSTEM) {
2166                Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
2167                return;
2168            }
2169            mOwners.removeProfileOwner(userHandle);
2170            mOwners.writeProfileOwner(userHandle);
2171
2172            DevicePolicyData policy = mUserData.get(userHandle);
2173            if (policy != null) {
2174                mUserData.remove(userHandle);
2175            }
2176            File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2177                    DEVICE_POLICIES_XML);
2178            policyFile.delete();
2179            Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
2180        }
2181        updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
2182    }
2183
2184    void loadOwners() {
2185        synchronized (this) {
2186            mOwners.load();
2187            setDeviceOwnerSystemPropertyLocked();
2188            findOwnerComponentIfNecessaryLocked();
2189            migrateUserRestrictionsIfNecessaryLocked();
2190            maybeSetDefaultDeviceOwnerUserRestrictionsLocked();
2191
2192            // TODO PO may not have a class name either due to b/17652534.  Address that too.
2193
2194            updateDeviceOwnerLocked();
2195        }
2196    }
2197
2198    /** Apply default restrictions that haven't been applied to device owners yet. */
2199    private void maybeSetDefaultDeviceOwnerUserRestrictionsLocked() {
2200        final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2201        if (deviceOwner != null) {
2202            maybeSetDefaultRestrictionsForAdminLocked(mOwners.getDeviceOwnerUserId(),
2203                    deviceOwner, UserRestrictionsUtils.getDefaultEnabledForDeviceOwner());
2204        }
2205    }
2206
2207    /** Apply default restrictions that haven't been applied to profile owners yet. */
2208    private void maybeSetDefaultProfileOwnerUserRestrictions() {
2209        synchronized (this) {
2210            for (final int userId : mOwners.getProfileOwnerKeys()) {
2211                final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
2212                // The following restrictions used to be applied to managed profiles by different
2213                // means (via Settings or by disabling components). Now they are proper user
2214                // restrictions so we apply them to managed profile owners. Non-managed secondary
2215                // users didn't have those restrictions so we skip them to keep existing behavior.
2216                if (profileOwner == null || !mUserManager.isManagedProfile(userId)) {
2217                    continue;
2218                }
2219                maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner,
2220                        UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
2221                ensureUnknownSourcesRestrictionForProfileOwnerLocked(
2222                        userId, profileOwner, false /* newOwner */);
2223            }
2224        }
2225    }
2226
2227    /**
2228     * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the
2229     * set of restrictions for this profile owner.
2230     */
2231    private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId,
2232            ActiveAdmin profileOwner, boolean newOwner) {
2233        if (newOwner || mInjector.settingsSecureGetIntForUser(
2234                Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
2235            profileOwner.ensureUserRestrictions().putBoolean(
2236                    UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
2237            saveUserRestrictionsLocked(userId);
2238            mInjector.settingsSecurePutIntForUser(
2239                    Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
2240        }
2241    }
2242
2243    /**
2244     * Apply default restrictions that haven't been applied to a given admin yet.
2245     */
2246    private void maybeSetDefaultRestrictionsForAdminLocked(
2247            int userId, ActiveAdmin admin, Set<String> defaultRestrictions) {
2248        if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
2249            return; // The same set of default restrictions has been already applied.
2250        }
2251        Slog.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId);
2252
2253        if (VERBOSE_LOG) {
2254            Slog.d(LOG_TAG,"Default enabled restrictions: "
2255                    + defaultRestrictions
2256                    + ". Restrictions already enabled: "
2257                    + admin.defaultEnabledRestrictionsAlreadySet);
2258        }
2259
2260        final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions);
2261        restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet);
2262        if (!restrictionsToSet.isEmpty()) {
2263            for (final String restriction : restrictionsToSet) {
2264                admin.ensureUserRestrictions().putBoolean(restriction, true);
2265            }
2266            admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet);
2267            Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet);
2268            saveUserRestrictionsLocked(userId);
2269        }
2270    }
2271
2272    private void setDeviceOwnerSystemPropertyLocked() {
2273        final boolean deviceProvisioned =
2274                mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0;
2275        final boolean hasDeviceOwner = mOwners.hasDeviceOwner();
2276        // If the device is not provisioned and there is currently no device owner, do not set the
2277        // read-only system property yet, since Device owner may still be provisioned.
2278        if (!hasDeviceOwner && !deviceProvisioned) {
2279            return;
2280        }
2281        // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
2282        // always false at this point.
2283        if (StorageManager.inCryptKeeperBounce()) {
2284            return;
2285        }
2286
2287        if (!mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT, "").isEmpty()) {
2288            Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
2289        } else {
2290            final String value = Boolean.toString(hasDeviceOwner);
2291            mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, value);
2292            Slog.i(LOG_TAG, "Set ro.device_owner property to " + value);
2293
2294            if (hasDeviceOwner && mInjector.securityLogGetLoggingEnabledProperty()) {
2295                mSecurityLogMonitor.start();
2296                maybePauseDeviceWideLoggingLocked();
2297            }
2298        }
2299    }
2300
2301    private void findOwnerComponentIfNecessaryLocked() {
2302        if (!mOwners.hasDeviceOwner()) {
2303            return;
2304        }
2305        final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
2306
2307        if (!TextUtils.isEmpty(doComponentName.getClassName())) {
2308            return; // Already a full component name.
2309        }
2310
2311        final ComponentName doComponent = findAdminComponentWithPackageLocked(
2312                doComponentName.getPackageName(),
2313                mOwners.getDeviceOwnerUserId());
2314        if (doComponent == null) {
2315            Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
2316        } else {
2317            mOwners.setDeviceOwnerWithRestrictionsMigrated(
2318                    doComponent,
2319                    mOwners.getDeviceOwnerName(),
2320                    mOwners.getDeviceOwnerUserId(),
2321                    !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
2322            mOwners.writeDeviceOwner();
2323            if (VERBOSE_LOG) {
2324                Log.v(LOG_TAG, "Device owner component filled in");
2325            }
2326        }
2327    }
2328
2329    /**
2330     * We didn't use to persist user restrictions for each owners but only persisted in user
2331     * manager.
2332     */
2333    private void migrateUserRestrictionsIfNecessaryLocked() {
2334        boolean migrated = false;
2335        // Migrate for the DO.  Basically all restrictions should be considered to be set by DO,
2336        // except for the "system controlled" ones.
2337        if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
2338            if (VERBOSE_LOG) {
2339                Log.v(LOG_TAG, "Migrating DO user restrictions");
2340            }
2341            migrated = true;
2342
2343            // Migrate user 0 restrictions to DO.
2344            final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
2345
2346            migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
2347                    /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
2348
2349            // Push DO user restrictions to user manager.
2350            pushUserRestrictions(UserHandle.USER_SYSTEM);
2351
2352            mOwners.setDeviceOwnerUserRestrictionsMigrated();
2353        }
2354
2355        // Migrate for POs.
2356
2357        // The following restrictions can be set on secondary users by the device owner, so we
2358        // assume they're not from the PO.
2359        final Set<String> secondaryUserExceptionList = Sets.newArraySet(
2360                UserManager.DISALLOW_OUTGOING_CALLS,
2361                UserManager.DISALLOW_SMS);
2362
2363        for (UserInfo ui : mUserManager.getUsers()) {
2364            final int userId = ui.id;
2365            if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
2366                if (VERBOSE_LOG) {
2367                    Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
2368                }
2369                migrated = true;
2370
2371                final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
2372
2373                final Set<String> exceptionList =
2374                        (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
2375
2376                migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
2377                        exceptionList, /* isDeviceOwner =*/ false);
2378
2379                // Note if a secondary user has no PO but has a DA that disables camera, we
2380                // don't get here and won't push the camera user restriction to UserManager
2381                // here.  That's okay because we'll push user restrictions anyway when a user
2382                // starts.  But we still do it because we want to let user manager persist
2383                // upon migration.
2384                pushUserRestrictions(userId);
2385
2386                mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
2387            }
2388        }
2389        if (VERBOSE_LOG && migrated) {
2390            Log.v(LOG_TAG, "User restrictions migrated.");
2391        }
2392    }
2393
2394    private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
2395            Set<String> exceptionList, boolean isDeviceOwner) {
2396        final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
2397                user.getIdentifier());
2398
2399        final Bundle newBaseRestrictions = new Bundle();
2400        final Bundle newOwnerRestrictions = new Bundle();
2401
2402        for (String key : origRestrictions.keySet()) {
2403            if (!origRestrictions.getBoolean(key)) {
2404                continue;
2405            }
2406            final boolean canOwnerChange = isDeviceOwner
2407                    ? UserRestrictionsUtils.canDeviceOwnerChange(key)
2408                    : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
2409
2410            if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
2411                newBaseRestrictions.putBoolean(key, true);
2412            } else {
2413                newOwnerRestrictions.putBoolean(key, true);
2414            }
2415        }
2416
2417        if (VERBOSE_LOG) {
2418            Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
2419            Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
2420            Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
2421        }
2422        mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
2423                newBaseRestrictions);
2424
2425        if (admin != null) {
2426            admin.ensureUserRestrictions().clear();
2427            admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
2428        } else {
2429            Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
2430        }
2431        saveSettingsLocked(user.getIdentifier());
2432    }
2433
2434    private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
2435        final DevicePolicyData policy = getUserData(userId);
2436        final int n = policy.mAdminList.size();
2437        ComponentName found = null;
2438        int nFound = 0;
2439        for (int i = 0; i < n; i++) {
2440            final ActiveAdmin admin = policy.mAdminList.get(i);
2441            if (packageName.equals(admin.info.getPackageName())) {
2442                // Found!
2443                if (nFound == 0) {
2444                    found = admin.info.getComponent();
2445                }
2446                nFound++;
2447            }
2448        }
2449        if (nFound > 1) {
2450            Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
2451        }
2452        return found;
2453    }
2454
2455    /**
2456     * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
2457     * reminders.  Clears alarm if no expirations are configured.
2458     */
2459    private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
2460        final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
2461        final long now = System.currentTimeMillis();
2462        final long timeToExpire = expiration - now;
2463        final long alarmTime;
2464        if (expiration == 0) {
2465            // No expirations are currently configured:  Cancel alarm.
2466            alarmTime = 0;
2467        } else if (timeToExpire <= 0) {
2468            // The password has already expired:  Repeat every 24 hours.
2469            alarmTime = now + MS_PER_DAY;
2470        } else {
2471            // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
2472            // the expiration time.
2473            long alarmInterval = timeToExpire % MS_PER_DAY;
2474            if (alarmInterval == 0) {
2475                alarmInterval = MS_PER_DAY;
2476            }
2477            alarmTime = now + alarmInterval;
2478        }
2479
2480        long token = mInjector.binderClearCallingIdentity();
2481        try {
2482            int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
2483            AlarmManager am = mInjector.getAlarmManager();
2484            PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2485                    new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2486                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
2487                    UserHandle.of(affectedUserHandle));
2488            am.cancel(pi);
2489            if (alarmTime != 0) {
2490                am.set(AlarmManager.RTC, alarmTime, pi);
2491            }
2492        } finally {
2493            mInjector.binderRestoreCallingIdentity(token);
2494        }
2495    }
2496
2497    ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2498        ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2499        if (admin != null
2500                && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2501                && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2502            return admin;
2503        }
2504        return null;
2505    }
2506
2507    ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2508        if (parent) {
2509            enforceManagedProfile(userHandle, "call APIs on the parent profile");
2510        }
2511        ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2512        if (admin != null && parent) {
2513            admin = admin.getParentActiveAdmin();
2514        }
2515        return admin;
2516    }
2517
2518    ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2519            throws SecurityException {
2520        final int callingUid = mInjector.binderGetCallingUid();
2521
2522        ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
2523        if (result != null) {
2524            return result;
2525        }
2526
2527        if (who != null) {
2528            final int userId = UserHandle.getUserId(callingUid);
2529            final DevicePolicyData policy = getUserData(userId);
2530            ActiveAdmin admin = policy.mAdminMap.get(who);
2531            if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2532                throw new SecurityException("Admin " + admin.info.getComponent()
2533                         + " does not own the device");
2534            }
2535            if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2536                throw new SecurityException("Admin " + admin.info.getComponent()
2537                        + " does not own the profile");
2538            }
2539            throw new SecurityException("Admin " + admin.info.getComponent()
2540                    + " did not specify uses-policy for: "
2541                    + admin.info.getTagForPolicy(reqPolicy));
2542        } else {
2543            throw new SecurityException("No active admin owned by uid "
2544                    + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
2545        }
2546    }
2547
2548    ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2549            throws SecurityException {
2550        if (parent) {
2551            enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2552                    "call APIs on the parent profile");
2553        }
2554        ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2555        return parent ? admin.getParentActiveAdmin() : admin;
2556    }
2557    /**
2558     * Find the admin for the component and userId bit of the uid, then check
2559     * the admin's uid matches the uid.
2560     */
2561    private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2562        final int userId = UserHandle.getUserId(uid);
2563        final DevicePolicyData policy = getUserData(userId);
2564        ActiveAdmin admin = policy.mAdminMap.get(who);
2565        if (admin == null) {
2566            throw new SecurityException("No active admin " + who);
2567        }
2568        if (admin.getUid() != uid) {
2569            throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2570        }
2571        return admin;
2572    }
2573
2574    private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2575            int uid) {
2576        // Try to find an admin which can use reqPolicy
2577        final int userId = UserHandle.getUserId(uid);
2578        final DevicePolicyData policy = getUserData(userId);
2579        if (who != null) {
2580            ActiveAdmin admin = policy.mAdminMap.get(who);
2581            if (admin == null) {
2582                throw new SecurityException("No active admin " + who);
2583            }
2584            if (admin.getUid() != uid) {
2585                throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2586            }
2587            if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2588                return admin;
2589            }
2590        } else {
2591            for (ActiveAdmin admin : policy.mAdminList) {
2592                if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2593                        userId)) {
2594                    return admin;
2595                }
2596            }
2597        }
2598
2599        return null;
2600    }
2601
2602    @VisibleForTesting
2603    boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2604            int userId) {
2605        final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2606        final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2607
2608        if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2609            return ownsDevice;
2610        } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2611            // DO always has the PO power.
2612            return ownsDevice || ownsProfile;
2613        } else {
2614            return admin.info.usesPolicy(reqPolicy);
2615        }
2616    }
2617
2618    void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2619        sendAdminCommandLocked(admin, action, null);
2620    }
2621
2622    void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2623        sendAdminCommandLocked(admin, action, null, result);
2624    }
2625
2626    void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2627            BroadcastReceiver result) {
2628        sendAdminCommandLocked(admin, action, adminExtras, result, false);
2629    }
2630
2631    /**
2632     * Send an update to one specific admin, get notified when that admin returns a result.
2633     *
2634     * @return whether the broadcast was successfully sent
2635     */
2636    boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2637            BroadcastReceiver result, boolean inForeground) {
2638        Intent intent = new Intent(action);
2639        intent.setComponent(admin.info.getComponent());
2640        if (UserManager.isDeviceInDemoMode(mContext)) {
2641            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2642        }
2643        if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2644            intent.putExtra("expiration", admin.passwordExpirationDate);
2645        }
2646        if (inForeground) {
2647            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2648        }
2649        if (adminExtras != null) {
2650            intent.putExtras(adminExtras);
2651        }
2652        if (mInjector.getPackageManager().queryBroadcastReceiversAsUser(
2653                intent,
2654                PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2655                admin.getUserHandle()).isEmpty()) {
2656            return false;
2657        }
2658        if (result != null) {
2659            mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2660                    null, result, mHandler, Activity.RESULT_OK, null, null);
2661        } else {
2662            mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2663        }
2664        return true;
2665    }
2666
2667    /**
2668     * Send an update to all admins of a user that enforce a specified policy.
2669     */
2670    void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) {
2671        final DevicePolicyData policy = getUserData(userHandle);
2672        final int count = policy.mAdminList.size();
2673        for (int i = 0; i < count; i++) {
2674            final ActiveAdmin admin = policy.mAdminList.get(i);
2675            if (admin.info.usesPolicy(reqPolicy)) {
2676                sendAdminCommandLocked(admin, action, adminExtras, null);
2677            }
2678        }
2679    }
2680
2681    /**
2682     * Send an update intent to all admins of a user and its profiles. Only send to admins that
2683     * enforce a specified policy.
2684     */
2685    private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2686            int userHandle, Bundle adminExtras) {
2687        int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2688        for (int profileId : profileIds) {
2689            sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras);
2690        }
2691    }
2692
2693    /**
2694     * Sends a broadcast to each profile that share the password unlock with the given user id.
2695     */
2696    private void sendAdminCommandForLockscreenPoliciesLocked(
2697            String action, int reqPolicy, int userHandle) {
2698        final Bundle extras = new Bundle();
2699        extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
2700        if (isSeparateProfileChallengeEnabled(userHandle)) {
2701            sendAdminCommandLocked(action, reqPolicy, userHandle, extras);
2702        } else {
2703            sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras);
2704        }
2705    }
2706
2707    void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2708        final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2709        DevicePolicyData policy = getUserData(userHandle);
2710        if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2711            policy.mRemovingAdmins.add(adminReceiver);
2712            sendAdminCommandLocked(admin,
2713                    DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2714                    new BroadcastReceiver() {
2715                        @Override
2716                        public void onReceive(Context context, Intent intent) {
2717                            removeAdminArtifacts(adminReceiver, userHandle);
2718                            removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2719                        }
2720                    });
2721        }
2722    }
2723
2724
2725    public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2726            boolean throwForMissingPermission) {
2727        if (!mHasFeature) {
2728            return null;
2729        }
2730        enforceFullCrossUsersPermission(userHandle);
2731        ActivityInfo ai = null;
2732        try {
2733            ai = mIPackageManager.getReceiverInfo(adminName,
2734                    PackageManager.GET_META_DATA |
2735                    PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2736                    PackageManager.MATCH_DIRECT_BOOT_AWARE |
2737                    PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2738        } catch (RemoteException e) {
2739            // shouldn't happen.
2740        }
2741        if (ai == null) {
2742            throw new IllegalArgumentException("Unknown admin: " + adminName);
2743        }
2744
2745        if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2746            final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2747                    + permission.BIND_DEVICE_ADMIN;
2748            Slog.w(LOG_TAG, message);
2749            if (throwForMissingPermission &&
2750                    ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2751                throw new IllegalArgumentException(message);
2752            }
2753        }
2754
2755        try {
2756            return new DeviceAdminInfo(mContext, ai);
2757        } catch (XmlPullParserException | IOException e) {
2758            Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2759                    e);
2760            return null;
2761        }
2762    }
2763
2764    private File getPolicyFileDirectory(@UserIdInt int userId) {
2765        return userId == UserHandle.USER_SYSTEM
2766                ? new File(mInjector.getDevicePolicyFilePathForSystemUser())
2767                : mInjector.environmentGetUserSystemDirectory(userId);
2768    }
2769
2770    private JournaledFile makeJournaledFile(@UserIdInt int userId) {
2771        final String base = new File(getPolicyFileDirectory(userId), DEVICE_POLICIES_XML)
2772                .getAbsolutePath();
2773        if (VERBOSE_LOG) {
2774            Log.v(LOG_TAG, "Opening " + base);
2775        }
2776        return new JournaledFile(new File(base), new File(base + ".tmp"));
2777    }
2778
2779    private void saveSettingsLocked(int userHandle) {
2780        DevicePolicyData policy = getUserData(userHandle);
2781        JournaledFile journal = makeJournaledFile(userHandle);
2782        FileOutputStream stream = null;
2783        try {
2784            stream = new FileOutputStream(journal.chooseForWrite(), false);
2785            XmlSerializer out = new FastXmlSerializer();
2786            out.setOutput(stream, StandardCharsets.UTF_8.name());
2787            out.startDocument(null, true);
2788
2789            out.startTag(null, "policies");
2790            if (policy.mRestrictionsProvider != null) {
2791                out.attribute(null, ATTR_PERMISSION_PROVIDER,
2792                        policy.mRestrictionsProvider.flattenToString());
2793            }
2794            if (policy.mUserSetupComplete) {
2795                out.attribute(null, ATTR_SETUP_COMPLETE,
2796                        Boolean.toString(true));
2797            }
2798            if (policy.mPaired) {
2799                out.attribute(null, ATTR_DEVICE_PAIRED,
2800                        Boolean.toString(true));
2801            }
2802            if (policy.mDeviceProvisioningConfigApplied) {
2803                out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2804                        Boolean.toString(true));
2805            }
2806            if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2807                out.attribute(null, ATTR_PROVISIONING_STATE,
2808                        Integer.toString(policy.mUserProvisioningState));
2809            }
2810            if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2811                out.attribute(null, ATTR_PERMISSION_POLICY,
2812                        Integer.toString(policy.mPermissionPolicy));
2813            }
2814
2815            // Serialize delegations.
2816            for (int i = 0; i < policy.mDelegationMap.size(); ++i) {
2817                final String delegatePackage = policy.mDelegationMap.keyAt(i);
2818                final List<String> scopes = policy.mDelegationMap.valueAt(i);
2819
2820                // Every "delegation" tag serializes the information of one delegate-scope pair.
2821                for (String scope : scopes) {
2822                    out.startTag(null, "delegation");
2823                    out.attribute(null, "delegatePackage", delegatePackage);
2824                    out.attribute(null, "scope", scope);
2825                    out.endTag(null, "delegation");
2826                }
2827            }
2828
2829            final int N = policy.mAdminList.size();
2830            for (int i=0; i<N; i++) {
2831                ActiveAdmin ap = policy.mAdminList.get(i);
2832                if (ap != null) {
2833                    out.startTag(null, "admin");
2834                    out.attribute(null, "name", ap.info.getComponent().flattenToString());
2835                    ap.writeToXml(out);
2836                    out.endTag(null, "admin");
2837                }
2838            }
2839
2840            if (policy.mPasswordOwner >= 0) {
2841                out.startTag(null, "password-owner");
2842                out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2843                out.endTag(null, "password-owner");
2844            }
2845
2846            if (policy.mFailedPasswordAttempts != 0) {
2847                out.startTag(null, "failed-password-attempts");
2848                out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2849                out.endTag(null, "failed-password-attempts");
2850            }
2851
2852            // For FDE devices only, we save this flag so we can report on password sufficiency
2853            // before the user enters their password for the first time after a reboot.  For
2854            // security reasons, we don't want to store the full set of active password metrics.
2855            if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2856                out.startTag(null, TAG_PASSWORD_VALIDITY);
2857                out.attribute(null, ATTR_VALUE,
2858                        Boolean.toString(policy.mPasswordValidAtLastCheckpoint));
2859                out.endTag(null, TAG_PASSWORD_VALIDITY);
2860            }
2861
2862            for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2863                out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2864                out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2865                out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2866            }
2867
2868            for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2869                String component = policy.mLockTaskPackages.get(i);
2870                out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2871                out.attribute(null, "name", component);
2872                out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2873            }
2874
2875            if (policy.mLockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
2876                out.startTag(null, TAG_LOCK_TASK_FEATURES);
2877                out.attribute(null, ATTR_VALUE, Integer.toString(policy.mLockTaskFeatures));
2878                out.endTag(null, TAG_LOCK_TASK_FEATURES);
2879            }
2880
2881            if (policy.mStatusBarDisabled) {
2882                out.startTag(null, TAG_STATUS_BAR);
2883                out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2884                out.endTag(null, TAG_STATUS_BAR);
2885            }
2886
2887            if (policy.doNotAskCredentialsOnBoot) {
2888                out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2889                out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2890            }
2891
2892            for (String id : policy.mAffiliationIds) {
2893                out.startTag(null, TAG_AFFILIATION_ID);
2894                out.attribute(null, ATTR_ID, id);
2895                out.endTag(null, TAG_AFFILIATION_ID);
2896            }
2897
2898            if (policy.mLastSecurityLogRetrievalTime >= 0) {
2899                out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2900                out.attribute(null, ATTR_VALUE,
2901                        Long.toString(policy.mLastSecurityLogRetrievalTime));
2902                out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2903            }
2904
2905            if (policy.mLastBugReportRequestTime >= 0) {
2906                out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2907                out.attribute(null, ATTR_VALUE,
2908                        Long.toString(policy.mLastBugReportRequestTime));
2909                out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2910            }
2911
2912            if (policy.mLastNetworkLogsRetrievalTime >= 0) {
2913                out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2914                out.attribute(null, ATTR_VALUE,
2915                        Long.toString(policy.mLastNetworkLogsRetrievalTime));
2916                out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2917            }
2918
2919            if (policy.mAdminBroadcastPending) {
2920                out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2921                out.attribute(null, ATTR_VALUE,
2922                        Boolean.toString(policy.mAdminBroadcastPending));
2923                out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2924            }
2925
2926            if (policy.mInitBundle != null) {
2927                out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2928                policy.mInitBundle.saveToXml(out);
2929                out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2930            }
2931
2932            if (policy.mPasswordTokenHandle != 0) {
2933                out.startTag(null, TAG_PASSWORD_TOKEN_HANDLE);
2934                out.attribute(null, ATTR_VALUE,
2935                        Long.toString(policy.mPasswordTokenHandle));
2936                out.endTag(null, TAG_PASSWORD_TOKEN_HANDLE);
2937            }
2938
2939            if (policy.mCurrentInputMethodSet) {
2940                out.startTag(null, TAG_CURRENT_INPUT_METHOD_SET);
2941                out.endTag(null, TAG_CURRENT_INPUT_METHOD_SET);
2942            }
2943
2944            if (!policy.mPrintingEnabled) {
2945                out.startTag(null, TAG_PRINTING_ENABLED);
2946                out.attribute(null, ATTR_VALUE, Boolean.toString(policy.mPrintingEnabled));
2947                out.endTag(null, TAG_PRINTING_ENABLED);
2948            }
2949
2950            for (final String cert : policy.mOwnerInstalledCaCerts) {
2951                out.startTag(null, TAG_OWNER_INSTALLED_CA_CERT);
2952                out.attribute(null, ATTR_ALIAS, cert);
2953                out.endTag(null, TAG_OWNER_INSTALLED_CA_CERT);
2954            }
2955
2956            out.endTag(null, "policies");
2957
2958            out.endDocument();
2959            stream.flush();
2960            FileUtils.sync(stream);
2961            stream.close();
2962            journal.commit();
2963            sendChangedNotification(userHandle);
2964        } catch (XmlPullParserException | IOException e) {
2965            Slog.w(LOG_TAG, "failed writing file", e);
2966            try {
2967                if (stream != null) {
2968                    stream.close();
2969                }
2970            } catch (IOException ex) {
2971                // Ignore
2972            }
2973            journal.rollback();
2974        }
2975    }
2976
2977    private void sendChangedNotification(int userHandle) {
2978        Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2979        intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2980        long ident = mInjector.binderClearCallingIdentity();
2981        try {
2982            mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2983        } finally {
2984            mInjector.binderRestoreCallingIdentity(ident);
2985        }
2986    }
2987
2988    private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2989        JournaledFile journal = makeJournaledFile(userHandle);
2990        FileInputStream stream = null;
2991        File file = journal.chooseForRead();
2992        boolean needsRewrite = false;
2993        try {
2994            stream = new FileInputStream(file);
2995            XmlPullParser parser = Xml.newPullParser();
2996            parser.setInput(stream, StandardCharsets.UTF_8.name());
2997
2998            int type;
2999            while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
3000                    && type != XmlPullParser.START_TAG) {
3001            }
3002            String tag = parser.getName();
3003            if (!"policies".equals(tag)) {
3004                throw new XmlPullParserException(
3005                        "Settings do not start with policies tag: found " + tag);
3006            }
3007
3008            // Extract the permission provider component name if available
3009            String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
3010            if (permissionProvider != null) {
3011                policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
3012            }
3013            String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
3014            if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
3015                policy.mUserSetupComplete = true;
3016            }
3017            String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
3018            if (paired != null && Boolean.toString(true).equals(paired)) {
3019                policy.mPaired = true;
3020            }
3021            String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
3022                    ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
3023            if (deviceProvisioningConfigApplied != null
3024                    && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
3025                policy.mDeviceProvisioningConfigApplied = true;
3026            }
3027            String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
3028            if (!TextUtils.isEmpty(provisioningState)) {
3029                policy.mUserProvisioningState = Integer.parseInt(provisioningState);
3030            }
3031            String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
3032            if (!TextUtils.isEmpty(permissionPolicy)) {
3033                policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
3034            }
3035            // Check for delegation compatibility with pre-O.
3036            // TODO(edmanp) remove in P.
3037            {
3038                final String certDelegate = parser.getAttributeValue(null,
3039                        ATTR_DELEGATED_CERT_INSTALLER);
3040                if (certDelegate != null) {
3041                    List<String> scopes = policy.mDelegationMap.get(certDelegate);
3042                    if (scopes == null) {
3043                        scopes = new ArrayList<>();
3044                        policy.mDelegationMap.put(certDelegate, scopes);
3045                    }
3046                    if (!scopes.contains(DELEGATION_CERT_INSTALL)) {
3047                        scopes.add(DELEGATION_CERT_INSTALL);
3048                        needsRewrite = true;
3049                    }
3050                }
3051                final String appRestrictionsDelegate = parser.getAttributeValue(null,
3052                        ATTR_APPLICATION_RESTRICTIONS_MANAGER);
3053                if (appRestrictionsDelegate != null) {
3054                    List<String> scopes = policy.mDelegationMap.get(appRestrictionsDelegate);
3055                    if (scopes == null) {
3056                        scopes = new ArrayList<>();
3057                        policy.mDelegationMap.put(appRestrictionsDelegate, scopes);
3058                    }
3059                    if (!scopes.contains(DELEGATION_APP_RESTRICTIONS)) {
3060                        scopes.add(DELEGATION_APP_RESTRICTIONS);
3061                        needsRewrite = true;
3062                    }
3063                }
3064            }
3065
3066            type = parser.next();
3067            int outerDepth = parser.getDepth();
3068            policy.mLockTaskPackages.clear();
3069            policy.mAdminList.clear();
3070            policy.mAdminMap.clear();
3071            policy.mAffiliationIds.clear();
3072            policy.mOwnerInstalledCaCerts.clear();
3073            while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
3074                   && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3075                if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3076                    continue;
3077                }
3078                tag = parser.getName();
3079                if ("admin".equals(tag)) {
3080                    String name = parser.getAttributeValue(null, "name");
3081                    try {
3082                        DeviceAdminInfo dai = findAdmin(
3083                                ComponentName.unflattenFromString(name), userHandle,
3084                                /* throwForMissingPermission= */ false);
3085                        if (VERBOSE_LOG
3086                                && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
3087                                != userHandle)) {
3088                            Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
3089                                    + dai.getActivityInfo().applicationInfo.uid + " for user "
3090                                    + userHandle);
3091                        }
3092                        if (dai != null) {
3093                            ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
3094                            ap.readFromXml(parser);
3095                            policy.mAdminMap.put(ap.info.getComponent(), ap);
3096                        }
3097                    } catch (RuntimeException e) {
3098                        Slog.w(LOG_TAG, "Failed loading admin " + name, e);
3099                    }
3100                } else if ("delegation".equals(tag)) {
3101                    // Parse delegation info.
3102                    final String delegatePackage = parser.getAttributeValue(null,
3103                            "delegatePackage");
3104                    final String scope = parser.getAttributeValue(null, "scope");
3105
3106                    // Get a reference to the scopes list for the delegatePackage.
3107                    List<String> scopes = policy.mDelegationMap.get(delegatePackage);
3108                    // Or make a new list if none was found.
3109                    if (scopes == null) {
3110                        scopes = new ArrayList<>();
3111                        policy.mDelegationMap.put(delegatePackage, scopes);
3112                    }
3113                    // Add the new scope to the list of delegatePackage if it's not already there.
3114                    if (!scopes.contains(scope)) {
3115                        scopes.add(scope);
3116                    }
3117                } else if ("failed-password-attempts".equals(tag)) {
3118                    policy.mFailedPasswordAttempts = Integer.parseInt(
3119                            parser.getAttributeValue(null, "value"));
3120                } else if ("password-owner".equals(tag)) {
3121                    policy.mPasswordOwner = Integer.parseInt(
3122                            parser.getAttributeValue(null, "value"));
3123                } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
3124                    policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
3125                } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
3126                    policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
3127                } else if (TAG_LOCK_TASK_FEATURES.equals(tag)) {
3128                    policy.mLockTaskFeatures = Integer.parseInt(
3129                            parser.getAttributeValue(null, ATTR_VALUE));
3130                } else if (TAG_STATUS_BAR.equals(tag)) {
3131                    policy.mStatusBarDisabled = Boolean.parseBoolean(
3132                            parser.getAttributeValue(null, ATTR_DISABLED));
3133                } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
3134                    policy.doNotAskCredentialsOnBoot = true;
3135                } else if (TAG_AFFILIATION_ID.equals(tag)) {
3136                    policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID));
3137                } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) {
3138                    policy.mLastSecurityLogRetrievalTime = Long.parseLong(
3139                            parser.getAttributeValue(null, ATTR_VALUE));
3140                } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) {
3141                    policy.mLastBugReportRequestTime = Long.parseLong(
3142                            parser.getAttributeValue(null, ATTR_VALUE));
3143                } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) {
3144                    policy.mLastNetworkLogsRetrievalTime = Long.parseLong(
3145                            parser.getAttributeValue(null, ATTR_VALUE));
3146                } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
3147                    String pending = parser.getAttributeValue(null, ATTR_VALUE);
3148                    policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
3149                } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
3150                    policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
3151                } else if ("active-password".equals(tag)) {
3152                    // Remove password metrics from saved settings, as we no longer wish to store
3153                    // these on disk
3154                    needsRewrite = true;
3155                } else if (TAG_PASSWORD_VALIDITY.equals(tag)) {
3156                    if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
3157                        // This flag is only used for FDE devices
3158                        policy.mPasswordValidAtLastCheckpoint = Boolean.parseBoolean(
3159                                parser.getAttributeValue(null, ATTR_VALUE));
3160                    }
3161                } else if (TAG_PASSWORD_TOKEN_HANDLE.equals(tag)) {
3162                    policy.mPasswordTokenHandle = Long.parseLong(
3163                            parser.getAttributeValue(null, ATTR_VALUE));
3164                } else if (TAG_CURRENT_INPUT_METHOD_SET.equals(tag)) {
3165                    policy.mCurrentInputMethodSet = true;
3166                } else if (TAG_OWNER_INSTALLED_CA_CERT.equals(tag)) {
3167                    policy.mOwnerInstalledCaCerts.add(parser.getAttributeValue(null, ATTR_ALIAS));
3168                } else if (TAG_PRINTING_ENABLED.equals(tag)) {
3169                    String enabled = parser.getAttributeValue(null, ATTR_VALUE);
3170                    policy.mPrintingEnabled = Boolean.toString(true).equals(enabled);
3171                } else {
3172                    Slog.w(LOG_TAG, "Unknown tag: " + tag);
3173                    XmlUtils.skipCurrentTag(parser);
3174                }
3175            }
3176        } catch (FileNotFoundException e) {
3177            // Don't be noisy, this is normal if we haven't defined any policies.
3178        } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
3179                | IndexOutOfBoundsException e) {
3180            Slog.w(LOG_TAG, "failed parsing " + file, e);
3181        }
3182        try {
3183            if (stream != null) {
3184                stream.close();
3185            }
3186        } catch (IOException e) {
3187            // Ignore
3188        }
3189
3190        // Generate a list of admins from the admin map
3191        policy.mAdminList.addAll(policy.mAdminMap.values());
3192
3193        // Might need to upgrade the file by rewriting it
3194        if (needsRewrite) {
3195            saveSettingsLocked(userHandle);
3196        }
3197
3198        validatePasswordOwnerLocked(policy);
3199        updateMaximumTimeToLockLocked(userHandle);
3200        updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
3201        updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle);
3202        if (policy.mStatusBarDisabled) {
3203            setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
3204        }
3205    }
3206
3207    private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
3208        long ident = mInjector.binderClearCallingIdentity();
3209        try {
3210            mInjector.getIActivityManager()
3211                    .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
3212        } catch (RemoteException e) {
3213            // Not gonna happen.
3214        } finally {
3215            mInjector.binderRestoreCallingIdentity(ident);
3216        }
3217    }
3218
3219    private void updateLockTaskFeaturesLocked(int flags, int userId) {
3220        long ident = mInjector.binderClearCallingIdentity();
3221        try {
3222            mInjector.getIActivityManager()
3223                    .updateLockTaskFeatures(userId, flags);
3224        } catch (RemoteException e) {
3225            // Not gonna happen.
3226        } finally {
3227            mInjector.binderRestoreCallingIdentity(ident);
3228        }
3229    }
3230
3231    private void updateDeviceOwnerLocked() {
3232        long ident = mInjector.binderClearCallingIdentity();
3233        try {
3234            // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
3235            // user id and also protect all other DAs too.
3236            final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
3237            if (deviceOwnerComponent != null) {
3238                mInjector.getIActivityManager()
3239                        .updateDeviceOwner(deviceOwnerComponent.getPackageName());
3240            }
3241        } catch (RemoteException e) {
3242            // Not gonna happen.
3243        } finally {
3244            mInjector.binderRestoreCallingIdentity(ident);
3245        }
3246    }
3247
3248    static void validateQualityConstant(int quality) {
3249        switch (quality) {
3250            case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
3251            case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
3252            case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
3253            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
3254            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
3255            case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
3256            case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
3257            case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
3258            case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
3259                return;
3260        }
3261        throw new IllegalArgumentException("Invalid quality constant: 0x"
3262                + Integer.toHexString(quality));
3263    }
3264
3265    void validatePasswordOwnerLocked(DevicePolicyData policy) {
3266        if (policy.mPasswordOwner >= 0) {
3267            boolean haveOwner = false;
3268            for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
3269                if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
3270                    haveOwner = true;
3271                    break;
3272                }
3273            }
3274            if (!haveOwner) {
3275                Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
3276                        + " no longer active; disabling");
3277                policy.mPasswordOwner = -1;
3278            }
3279        }
3280    }
3281
3282    @VisibleForTesting
3283    @Override
3284    void systemReady(int phase) {
3285        if (!mHasFeature) {
3286            return;
3287        }
3288        switch (phase) {
3289            case SystemService.PHASE_LOCK_SETTINGS_READY:
3290                onLockSettingsReady();
3291                loadAdminDataAsync();
3292                break;
3293            case SystemService.PHASE_BOOT_COMPLETED:
3294                ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
3295                break;
3296        }
3297    }
3298
3299    private void onLockSettingsReady() {
3300        getUserData(UserHandle.USER_SYSTEM);
3301        loadOwners();
3302        cleanUpOldUsers();
3303        maybeSetDefaultProfileOwnerUserRestrictions();
3304        handleStartUser(UserHandle.USER_SYSTEM);
3305
3306        // Register an observer for watching for user setup complete and settings changes.
3307        mSetupContentObserver.register();
3308        // Initialize the user setup state, to handle the upgrade case.
3309        updateUserSetupCompleteAndPaired();
3310
3311        List<String> packageList;
3312        synchronized (this) {
3313            packageList = getKeepUninstalledPackagesLocked();
3314        }
3315        if (packageList != null) {
3316            mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
3317        }
3318
3319        synchronized (this) {
3320            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
3321            if (deviceOwner != null) {
3322                // Push the force-ephemeral-users policy to the user manager.
3323                mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
3324
3325                // Update user switcher message to activity manager.
3326                ActivityManagerInternal activityManagerInternal =
3327                        mInjector.getActivityManagerInternal();
3328                activityManagerInternal.setSwitchingFromSystemUserMessage(
3329                        deviceOwner.startUserSessionMessage);
3330                activityManagerInternal.setSwitchingToSystemUserMessage(
3331                        deviceOwner.endUserSessionMessage);
3332            }
3333
3334            revertTransferOwnershipIfNecessaryLocked();
3335        }
3336    }
3337
3338    private void revertTransferOwnershipIfNecessaryLocked() {
3339        if (!mTransferOwnershipMetadataManager.metadataFileExists()) {
3340            return;
3341        }
3342        Slog.e(LOG_TAG, "Owner transfer metadata file exists! Reverting transfer.");
3343        final TransferOwnershipMetadataManager.Metadata metadata =
3344                mTransferOwnershipMetadataManager.loadMetadataFile();
3345        // Revert transfer
3346        if (metadata.adminType.equals(ADMIN_TYPE_PROFILE_OWNER)) {
3347            transferProfileOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3348                    metadata.userId);
3349            deleteTransferOwnershipMetadataFileLocked();
3350            deleteTransferOwnershipBundleLocked(metadata.userId);
3351        } else if (metadata.adminType.equals(ADMIN_TYPE_DEVICE_OWNER)) {
3352            transferDeviceOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3353                    metadata.userId);
3354            deleteTransferOwnershipMetadataFileLocked();
3355            deleteTransferOwnershipBundleLocked(metadata.userId);
3356        }
3357    }
3358
3359    private void ensureDeviceOwnerUserStarted() {
3360        final int userId;
3361        synchronized (this) {
3362            if (!mOwners.hasDeviceOwner()) {
3363                return;
3364            }
3365            userId = mOwners.getDeviceOwnerUserId();
3366        }
3367        if (VERBOSE_LOG) {
3368            Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
3369        }
3370        if (userId != UserHandle.USER_SYSTEM) {
3371            try {
3372                mInjector.getIActivityManager().startUserInBackground(userId);
3373
3374                // STOPSHIP Prevent the DO user from being killed.
3375
3376            } catch (RemoteException e) {
3377                Slog.w(LOG_TAG, "Exception starting user", e);
3378            }
3379        }
3380    }
3381
3382    @Override
3383    void handleStartUser(int userId) {
3384        updateScreenCaptureDisabledInWindowManager(userId,
3385                getScreenCaptureDisabled(null, userId));
3386        pushUserRestrictions(userId);
3387
3388        startOwnerService(userId, "start-user");
3389    }
3390
3391    @Override
3392    void handleUnlockUser(int userId) {
3393        startOwnerService(userId, "unlock-user");
3394    }
3395
3396    @Override
3397    void handleStopUser(int userId) {
3398        stopOwnerService(userId, "stop-user");
3399    }
3400
3401    private void startOwnerService(int userId, String actionForLog) {
3402        final ComponentName owner = getOwnerComponent(userId);
3403        if (owner != null) {
3404            mDeviceAdminServiceController.startServiceForOwner(
3405                    owner.getPackageName(), userId, actionForLog);
3406        }
3407    }
3408
3409    private void stopOwnerService(int userId, String actionForLog) {
3410        mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog);
3411    }
3412
3413    private void cleanUpOldUsers() {
3414        // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
3415        // before reboot
3416        Set<Integer> usersWithProfileOwners;
3417        Set<Integer> usersWithData;
3418        synchronized(this) {
3419            usersWithProfileOwners = mOwners.getProfileOwnerKeys();
3420            usersWithData = new ArraySet<>();
3421            for (int i = 0; i < mUserData.size(); i++) {
3422                usersWithData.add(mUserData.keyAt(i));
3423            }
3424        }
3425        List<UserInfo> allUsers = mUserManager.getUsers();
3426
3427        Set<Integer> deletedUsers = new ArraySet<>();
3428        deletedUsers.addAll(usersWithProfileOwners);
3429        deletedUsers.addAll(usersWithData);
3430        for (UserInfo userInfo : allUsers) {
3431            deletedUsers.remove(userInfo.id);
3432        }
3433        for (Integer userId : deletedUsers) {
3434            removeUserData(userId);
3435        }
3436    }
3437
3438    private void handlePasswordExpirationNotification(int userHandle) {
3439        final Bundle adminExtras = new Bundle();
3440        adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
3441
3442        synchronized (this) {
3443            final long now = System.currentTimeMillis();
3444
3445            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
3446                    userHandle, /* parent */ false);
3447            final int N = admins.size();
3448            for (int i = 0; i < N; i++) {
3449                ActiveAdmin admin = admins.get(i);
3450                if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
3451                        && admin.passwordExpirationTimeout > 0L
3452                        && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
3453                        && admin.passwordExpirationDate > 0L) {
3454                    sendAdminCommandLocked(admin,
3455                            DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null);
3456                }
3457            }
3458            setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
3459        }
3460    }
3461
3462    /**
3463     * Clean up internal state when the set of installed trusted CA certificates changes.
3464     *
3465     * @param userHandle user to check for. This must be a real user and not, for example,
3466     *        {@link UserHandle#ALL}.
3467     * @param installedCertificates the full set of certificate authorities currently installed for
3468     *        {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will
3469     *        correspond to some subset of this.
3470     */
3471    protected void onInstalledCertificatesChanged(final UserHandle userHandle,
3472            final @NonNull Collection<String> installedCertificates) {
3473        if (!mHasFeature) {
3474            return;
3475        }
3476        enforceManageUsers();
3477
3478        synchronized (this) {
3479            final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3480
3481            boolean changed = false;
3482            changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates);
3483            changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates);
3484            if (changed) {
3485                saveSettingsLocked(userHandle.getIdentifier());
3486            }
3487        }
3488    }
3489
3490    /**
3491     * Internal method used by {@link CertificateMonitor}.
3492     */
3493    protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) {
3494        if (!mHasFeature) {
3495            return Collections.<String> emptySet();
3496        }
3497        synchronized (this) {
3498            final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3499            return policy.mAcceptedCaCertificates;
3500        }
3501    }
3502
3503    /**
3504     * @param adminReceiver The admin to add
3505     * @param refreshing true = update an active admin, no error
3506     */
3507    @Override
3508    public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
3509        if (!mHasFeature) {
3510            return;
3511        }
3512        setActiveAdmin(adminReceiver, refreshing, userHandle, null);
3513    }
3514
3515    private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
3516            Bundle onEnableData) {
3517        mContext.enforceCallingOrSelfPermission(
3518                android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3519        enforceFullCrossUsersPermission(userHandle);
3520
3521        DevicePolicyData policy = getUserData(userHandle);
3522        DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
3523                /* throwForMissingPermission= */ true);
3524        synchronized (this) {
3525            checkActiveAdminPrecondition(adminReceiver, info, policy);
3526            long ident = mInjector.binderClearCallingIdentity();
3527            try {
3528                final ActiveAdmin existingAdmin
3529                        = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3530                if (!refreshing && existingAdmin != null) {
3531                    throw new IllegalArgumentException("Admin is already added");
3532                }
3533                ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
3534                newAdmin.testOnlyAdmin =
3535                        (existingAdmin != null) ? existingAdmin.testOnlyAdmin
3536                                : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
3537                policy.mAdminMap.put(adminReceiver, newAdmin);
3538                int replaceIndex = -1;
3539                final int N = policy.mAdminList.size();
3540                for (int i=0; i < N; i++) {
3541                    ActiveAdmin oldAdmin = policy.mAdminList.get(i);
3542                    if (oldAdmin.info.getComponent().equals(adminReceiver)) {
3543                        replaceIndex = i;
3544                        break;
3545                    }
3546                }
3547                if (replaceIndex == -1) {
3548                    policy.mAdminList.add(newAdmin);
3549                    enableIfNecessary(info.getPackageName(), userHandle);
3550                    mUsageStatsManagerInternal.onActiveAdminAdded(
3551                            adminReceiver.getPackageName(), userHandle);
3552                } else {
3553                    policy.mAdminList.set(replaceIndex, newAdmin);
3554                }
3555                saveSettingsLocked(userHandle);
3556                sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3557                        onEnableData, null);
3558            } finally {
3559                mInjector.binderRestoreCallingIdentity(ident);
3560            }
3561        }
3562    }
3563
3564    private void loadAdminDataAsync() {
3565        mInjector.postOnSystemServerInitThreadPool(() -> {
3566            pushActiveAdminPackages();
3567            mUsageStatsManagerInternal.onAdminDataAvailable();
3568            pushAllMeteredRestrictedPackages();
3569            mInjector.getNetworkPolicyManagerInternal().onAdminDataAvailable();
3570        });
3571    }
3572
3573    private void pushActiveAdminPackages() {
3574        synchronized (this) {
3575            final List<UserInfo> users = mUserManager.getUsers();
3576            for (int i = users.size() - 1; i >= 0; --i) {
3577                final int userId = users.get(i).id;
3578                mUsageStatsManagerInternal.setActiveAdminApps(
3579                        getActiveAdminPackagesLocked(userId), userId);
3580            }
3581        }
3582    }
3583
3584    private void pushAllMeteredRestrictedPackages() {
3585        synchronized (this) {
3586            final List<UserInfo> users = mUserManager.getUsers();
3587            for (int i = users.size() - 1; i >= 0; --i) {
3588                final int userId = users.get(i).id;
3589                mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackagesAsync(
3590                        getMeteredDisabledPackagesLocked(userId), userId);
3591            }
3592        }
3593    }
3594
3595    private void pushActiveAdminPackagesLocked(int userId) {
3596        mUsageStatsManagerInternal.setActiveAdminApps(
3597                getActiveAdminPackagesLocked(userId), userId);
3598    }
3599
3600    private Set<String> getActiveAdminPackagesLocked(int userId) {
3601        final DevicePolicyData policy = getUserData(userId);
3602        Set<String> adminPkgs = null;
3603        for (int i = policy.mAdminList.size() - 1; i >= 0; --i) {
3604            final String pkgName = policy.mAdminList.get(i).info.getPackageName();
3605            if (adminPkgs == null) {
3606                adminPkgs = new ArraySet<>();
3607            }
3608            adminPkgs.add(pkgName);
3609        }
3610        return adminPkgs;
3611    }
3612
3613    private void transferActiveAdminUncheckedLocked(ComponentName incomingReceiver,
3614            ComponentName outgoingReceiver, int userHandle) {
3615        final DevicePolicyData policy = getUserData(userHandle);
3616        if (!policy.mAdminMap.containsKey(outgoingReceiver)
3617                && policy.mAdminMap.containsKey(incomingReceiver)) {
3618            // Nothing to transfer - the incoming receiver is already the active admin.
3619            return;
3620        }
3621        final DeviceAdminInfo incomingDeviceInfo = findAdmin(incomingReceiver, userHandle,
3622            /* throwForMissingPermission= */ true);
3623        final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver);
3624        final int oldAdminUid = adminToTransfer.getUid();
3625
3626        adminToTransfer.transfer(incomingDeviceInfo);
3627        policy.mAdminMap.remove(outgoingReceiver);
3628        policy.mAdminMap.put(incomingReceiver, adminToTransfer);
3629        if (policy.mPasswordOwner == oldAdminUid) {
3630            policy.mPasswordOwner = adminToTransfer.getUid();
3631        }
3632
3633        saveSettingsLocked(userHandle);
3634        sendAdminCommandLocked(adminToTransfer, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3635                null, null);
3636    }
3637
3638    private void checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info,
3639            DevicePolicyData policy) {
3640        if (info == null) {
3641            throw new IllegalArgumentException("Bad admin: " + adminReceiver);
3642        }
3643        if (!info.getActivityInfo().applicationInfo.isInternal()) {
3644            throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
3645                    + adminReceiver);
3646        }
3647        if (info.getActivityInfo().applicationInfo.isInstantApp()) {
3648            throw new IllegalArgumentException("Instant apps cannot be device admins: "
3649                    + adminReceiver);
3650        }
3651        if (policy.mRemovingAdmins.contains(adminReceiver)) {
3652            throw new IllegalArgumentException(
3653                    "Trying to set an admin which is being removed");
3654        }
3655    }
3656
3657    @Override
3658    public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
3659        if (!mHasFeature) {
3660            return false;
3661        }
3662        enforceFullCrossUsersPermission(userHandle);
3663        synchronized (this) {
3664            return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
3665        }
3666    }
3667
3668    @Override
3669    public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
3670        if (!mHasFeature) {
3671            return false;
3672        }
3673        enforceFullCrossUsersPermission(userHandle);
3674        synchronized (this) {
3675            DevicePolicyData policyData = getUserData(userHandle);
3676            return policyData.mRemovingAdmins.contains(adminReceiver);
3677        }
3678    }
3679
3680    @Override
3681    public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
3682        if (!mHasFeature) {
3683            return false;
3684        }
3685        enforceFullCrossUsersPermission(userHandle);
3686        synchronized (this) {
3687            ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3688            if (administrator == null) {
3689                throw new SecurityException("No active admin " + adminReceiver);
3690            }
3691            return administrator.info.usesPolicy(policyId);
3692        }
3693    }
3694
3695    @Override
3696    @SuppressWarnings("unchecked")
3697    public List<ComponentName> getActiveAdmins(int userHandle) {
3698        if (!mHasFeature) {
3699            return Collections.EMPTY_LIST;
3700        }
3701
3702        enforceFullCrossUsersPermission(userHandle);
3703        synchronized (this) {
3704            DevicePolicyData policy = getUserData(userHandle);
3705            final int N = policy.mAdminList.size();
3706            if (N <= 0) {
3707                return null;
3708            }
3709            ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3710            for (int i=0; i<N; i++) {
3711                res.add(policy.mAdminList.get(i).info.getComponent());
3712            }
3713            return res;
3714        }
3715    }
3716
3717    @Override
3718    public boolean packageHasActiveAdmins(String packageName, int userHandle) {
3719        if (!mHasFeature) {
3720            return false;
3721        }
3722        enforceFullCrossUsersPermission(userHandle);
3723        synchronized (this) {
3724            DevicePolicyData policy = getUserData(userHandle);
3725            final int N = policy.mAdminList.size();
3726            for (int i=0; i<N; i++) {
3727                if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
3728                    return true;
3729                }
3730            }
3731            return false;
3732        }
3733    }
3734
3735    @Override
3736    public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
3737        if (!mHasFeature) {
3738            return;
3739        }
3740        Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
3741        enforceShell("forceRemoveActiveAdmin");
3742        long ident = mInjector.binderClearCallingIdentity();
3743        try {
3744            synchronized (this)  {
3745                if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
3746                    throw new SecurityException("Attempt to remove non-test admin "
3747                            + adminReceiver + " " + userHandle);
3748                }
3749
3750                // If admin is a device or profile owner tidy that up first.
3751                if (isDeviceOwner(adminReceiver, userHandle)) {
3752                    clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3753                }
3754                if (isProfileOwner(adminReceiver, userHandle)) {
3755                    final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3756                            userHandle, /* parent */ false);
3757                    clearProfileOwnerLocked(admin, userHandle);
3758                }
3759            }
3760            // Remove the admin skipping sending the broadcast.
3761            removeAdminArtifacts(adminReceiver, userHandle);
3762            Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3763        } finally {
3764            mInjector.binderRestoreCallingIdentity(ident);
3765        }
3766    }
3767
3768    private void clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle) {
3769        // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state
3770        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
3771            mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle);
3772        }
3773    }
3774
3775    /**
3776     * Return if a given package has testOnly="true", in which case we'll relax certain rules
3777     * for CTS.
3778     *
3779     * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
3780     * to check wehter an active admin is test-only or not.
3781     *
3782     * The system allows this flag to be changed when an app is updated, which is not good
3783     * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3784     * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3785     */
3786    private boolean isPackageTestOnly(String packageName, int userHandle) {
3787        final ApplicationInfo ai;
3788        try {
3789            ai = mInjector.getIPackageManager().getApplicationInfo(packageName,
3790                    (PackageManager.MATCH_DIRECT_BOOT_AWARE
3791                            | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3792        } catch (RemoteException e) {
3793            throw new IllegalStateException(e);
3794        }
3795        if (ai == null) {
3796            throw new IllegalStateException("Couldn't find package: "
3797                    + packageName + " on user " + userHandle);
3798        }
3799        return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3800    }
3801
3802    /**
3803     * See {@link #isPackageTestOnly}.
3804     */
3805    private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3806        final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3807        return (admin != null) && admin.testOnlyAdmin;
3808    }
3809
3810    private void enforceShell(String method) {
3811        final int callingUid = mInjector.binderGetCallingUid();
3812        if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3813            throw new SecurityException("Non-shell user attempted to call " + method);
3814        }
3815    }
3816
3817    @Override
3818    public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3819        if (!mHasFeature) {
3820            return;
3821        }
3822        enforceFullCrossUsersPermission(userHandle);
3823        enforceUserUnlocked(userHandle);
3824        synchronized (this) {
3825            ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3826            if (admin == null) {
3827                return;
3828            }
3829            // Active device/profile owners must remain active admins.
3830            if (isDeviceOwner(adminReceiver, userHandle)
3831                    || isProfileOwner(adminReceiver, userHandle)) {
3832                Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3833                        adminReceiver);
3834                return;
3835            }
3836            if (admin.getUid() != mInjector.binderGetCallingUid()) {
3837                mContext.enforceCallingOrSelfPermission(
3838                        android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3839            }
3840            long ident = mInjector.binderClearCallingIdentity();
3841            try {
3842                removeActiveAdminLocked(adminReceiver, userHandle);
3843            } finally {
3844                mInjector.binderRestoreCallingIdentity(ident);
3845            }
3846        }
3847    }
3848
3849    @Override
3850    public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3851        ComponentName profileOwner = getProfileOwner(userHandle);
3852        // Profile challenge is supported on N or newer release.
3853        return profileOwner != null &&
3854                getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3855    }
3856
3857    @Override
3858    public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3859        if (!mHasFeature) {
3860            return;
3861        }
3862        Preconditions.checkNotNull(who, "ComponentName is null");
3863        validateQualityConstant(quality);
3864
3865        synchronized (this) {
3866            ActiveAdmin ap = getActiveAdminForCallerLocked(
3867                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3868            if (ap.minimumPasswordMetrics.quality != quality) {
3869                ap.minimumPasswordMetrics.quality = quality;
3870                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3871                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3872            }
3873        }
3874    }
3875
3876    /**
3877     * Updates flag in memory that tells us whether the user's password currently satisfies the
3878     * requirements set by all of the user's active admins.  This should be called before
3879     * {@link #saveSettingsLocked} whenever the password or the admin policies have changed.
3880     */
3881    @GuardedBy("DevicePolicyManagerService.this")
3882    private void updatePasswordValidityCheckpointLocked(int userHandle) {
3883        DevicePolicyData policy = getUserData(userHandle);
3884        policy.mPasswordValidAtLastCheckpoint = isActivePasswordSufficientForUserLocked(
3885                policy, policy.mUserHandle, false);
3886    }
3887
3888    @Override
3889    public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3890        if (!mHasFeature) {
3891            return PASSWORD_QUALITY_UNSPECIFIED;
3892        }
3893        enforceFullCrossUsersPermission(userHandle);
3894        synchronized (this) {
3895            int mode = PASSWORD_QUALITY_UNSPECIFIED;
3896
3897            if (who != null) {
3898                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3899                return admin != null ? admin.minimumPasswordMetrics.quality : mode;
3900            }
3901
3902            // Return the strictest policy across all participating admins.
3903            List<ActiveAdmin> admins =
3904                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3905            final int N = admins.size();
3906            for (int i = 0; i < N; i++) {
3907                ActiveAdmin admin = admins.get(i);
3908                if (mode < admin.minimumPasswordMetrics.quality) {
3909                    mode = admin.minimumPasswordMetrics.quality;
3910                }
3911            }
3912            return mode;
3913        }
3914    }
3915
3916    private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3917            int userHandle, boolean parent) {
3918        if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3919            // If this user has a separate challenge, only return its restrictions.
3920            return getUserDataUnchecked(userHandle).mAdminList;
3921        } else {
3922            // Return all admins for this user and the profiles that are visible from this
3923            // user that do not use a separate work challenge.
3924            ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3925            for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3926                DevicePolicyData policy = getUserData(userInfo.id);
3927                if (!userInfo.isManagedProfile()) {
3928                    admins.addAll(policy.mAdminList);
3929                } else {
3930                    // For managed profiles, we always include the policies set on the parent
3931                    // profile. Additionally, we include the ones set on the managed profile
3932                    // if no separate challenge is in place.
3933                    boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3934                    final int N = policy.mAdminList.size();
3935                    for (int i = 0; i < N; i++) {
3936                        ActiveAdmin admin = policy.mAdminList.get(i);
3937                        if (admin.hasParentActiveAdmin()) {
3938                            admins.add(admin.getParentActiveAdmin());
3939                        }
3940                        if (!hasSeparateChallenge) {
3941                            admins.add(admin);
3942                        }
3943                    }
3944                }
3945            }
3946            return admins;
3947        }
3948    }
3949
3950    private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3951        long ident = mInjector.binderClearCallingIdentity();
3952        try {
3953            return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3954        } finally {
3955            mInjector.binderRestoreCallingIdentity(ident);
3956        }
3957    }
3958
3959    @Override
3960    public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3961        if (!mHasFeature) {
3962            return;
3963        }
3964        Preconditions.checkNotNull(who, "ComponentName is null");
3965        synchronized (this) {
3966            ActiveAdmin ap = getActiveAdminForCallerLocked(
3967                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3968            if (ap.minimumPasswordMetrics.length != length) {
3969                ap.minimumPasswordMetrics.length = length;
3970                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3971                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3972            }
3973        }
3974    }
3975
3976    @Override
3977    public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3978        return getStrictestPasswordRequirement(who, userHandle, parent,
3979                admin -> admin.minimumPasswordMetrics.length, PASSWORD_QUALITY_UNSPECIFIED);
3980    }
3981
3982    @Override
3983    public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3984        if (!mHasFeature) {
3985            return;
3986        }
3987        Preconditions.checkNotNull(who, "ComponentName is null");
3988        synchronized (this) {
3989            ActiveAdmin ap = getActiveAdminForCallerLocked(
3990                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3991            if (ap.passwordHistoryLength != length) {
3992                ap.passwordHistoryLength = length;
3993                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3994                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3995            }
3996        }
3997    }
3998
3999    @Override
4000    public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
4001        return getStrictestPasswordRequirement(who, userHandle, parent,
4002                admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED);
4003    }
4004
4005    @Override
4006    public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
4007        if (!mHasFeature) {
4008            return;
4009        }
4010        Preconditions.checkNotNull(who, "ComponentName is null");
4011        Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
4012        final int userHandle = mInjector.userHandleGetCallingUserId();
4013        synchronized (this) {
4014            ActiveAdmin ap = getActiveAdminForCallerLocked(
4015                    who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
4016            // Calling this API automatically bumps the expiration date
4017            final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4018            ap.passwordExpirationDate = expiration;
4019            ap.passwordExpirationTimeout = timeout;
4020            if (timeout > 0L) {
4021                Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
4022                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
4023                        .format(new Date(expiration)));
4024            }
4025            saveSettingsLocked(userHandle);
4026
4027            // in case this is the first one, set the alarm on the appropriate user.
4028            setExpirationAlarmCheckLocked(mContext, userHandle, parent);
4029        }
4030    }
4031
4032    /**
4033     * Return a single admin's expiration cycle time, or the min of all cycle times.
4034     * Returns 0 if not configured.
4035     */
4036    @Override
4037    public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
4038        if (!mHasFeature) {
4039            return 0L;
4040        }
4041        enforceFullCrossUsersPermission(userHandle);
4042        synchronized (this) {
4043            long timeout = 0L;
4044
4045            if (who != null) {
4046                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4047                return admin != null ? admin.passwordExpirationTimeout : timeout;
4048            }
4049
4050            // Return the strictest policy across all participating admins.
4051            List<ActiveAdmin> admins =
4052                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4053            final int N = admins.size();
4054            for (int i = 0; i < N; i++) {
4055                ActiveAdmin admin = admins.get(i);
4056                if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
4057                        && timeout > admin.passwordExpirationTimeout)) {
4058                    timeout = admin.passwordExpirationTimeout;
4059                }
4060            }
4061            return timeout;
4062        }
4063    }
4064
4065    @Override
4066    public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4067        final int userId = UserHandle.getCallingUserId();
4068        List<String> changedProviders = null;
4069
4070        synchronized (this) {
4071            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4072                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4073            if (activeAdmin.crossProfileWidgetProviders == null) {
4074                activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
4075            }
4076            List<String> providers = activeAdmin.crossProfileWidgetProviders;
4077            if (!providers.contains(packageName)) {
4078                providers.add(packageName);
4079                changedProviders = new ArrayList<>(providers);
4080                saveSettingsLocked(userId);
4081            }
4082        }
4083
4084        if (changedProviders != null) {
4085            mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
4086            return true;
4087        }
4088
4089        return false;
4090    }
4091
4092    @Override
4093    public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4094        final int userId = UserHandle.getCallingUserId();
4095        List<String> changedProviders = null;
4096
4097        synchronized (this) {
4098            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4099                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4100            if (activeAdmin.crossProfileWidgetProviders == null
4101                    || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4102                return false;
4103            }
4104            List<String> providers = activeAdmin.crossProfileWidgetProviders;
4105            if (providers.remove(packageName)) {
4106                changedProviders = new ArrayList<>(providers);
4107                saveSettingsLocked(userId);
4108            }
4109        }
4110
4111        if (changedProviders != null) {
4112            mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
4113            return true;
4114        }
4115
4116        return false;
4117    }
4118
4119    @Override
4120    public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
4121        synchronized (this) {
4122            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4123                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4124            if (activeAdmin.crossProfileWidgetProviders == null
4125                    || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4126                return null;
4127            }
4128            if (mInjector.binderIsCallingUidMyUid()) {
4129                return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
4130            } else {
4131                return activeAdmin.crossProfileWidgetProviders;
4132            }
4133        }
4134    }
4135
4136    /**
4137     * Return a single admin's expiration date/time, or the min (soonest) for all admins.
4138     * Returns 0 if not configured.
4139     */
4140    private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
4141        long timeout = 0L;
4142
4143        if (who != null) {
4144            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4145            return admin != null ? admin.passwordExpirationDate : timeout;
4146        }
4147
4148        // Return the strictest policy across all participating admins.
4149        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4150        final int N = admins.size();
4151        for (int i = 0; i < N; i++) {
4152            ActiveAdmin admin = admins.get(i);
4153            if (timeout == 0L || (admin.passwordExpirationDate != 0
4154                    && timeout > admin.passwordExpirationDate)) {
4155                timeout = admin.passwordExpirationDate;
4156            }
4157        }
4158        return timeout;
4159    }
4160
4161    @Override
4162    public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
4163        if (!mHasFeature) {
4164            return 0L;
4165        }
4166        enforceFullCrossUsersPermission(userHandle);
4167        synchronized (this) {
4168            return getPasswordExpirationLocked(who, userHandle, parent);
4169        }
4170    }
4171
4172    @Override
4173    public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
4174        if (!mHasFeature) {
4175            return;
4176        }
4177        Preconditions.checkNotNull(who, "ComponentName is null");
4178        synchronized (this) {
4179            ActiveAdmin ap = getActiveAdminForCallerLocked(
4180                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4181            if (ap.minimumPasswordMetrics.upperCase != length) {
4182                ap.minimumPasswordMetrics.upperCase = length;
4183                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
4184                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4185            }
4186        }
4187    }
4188
4189    @Override
4190    public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
4191        return getStrictestPasswordRequirement(who, userHandle, parent,
4192                admin -> admin.minimumPasswordMetrics.upperCase, PASSWORD_QUALITY_COMPLEX);
4193    }
4194
4195    @Override
4196    public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
4197        Preconditions.checkNotNull(who, "ComponentName is null");
4198        synchronized (this) {
4199            ActiveAdmin ap = getActiveAdminForCallerLocked(
4200                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4201            if (ap.minimumPasswordMetrics.lowerCase != length) {
4202                ap.minimumPasswordMetrics.lowerCase = length;
4203                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
4204                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4205            }
4206        }
4207    }
4208
4209    @Override
4210    public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
4211        return getStrictestPasswordRequirement(who, userHandle, parent,
4212                admin -> admin.minimumPasswordMetrics.lowerCase, PASSWORD_QUALITY_COMPLEX);
4213    }
4214
4215    @Override
4216    public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
4217        if (!mHasFeature) {
4218            return;
4219        }
4220        Preconditions.checkNotNull(who, "ComponentName is null");
4221        synchronized (this) {
4222            ActiveAdmin ap = getActiveAdminForCallerLocked(
4223                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4224            if (ap.minimumPasswordMetrics.letters != length) {
4225                ap.minimumPasswordMetrics.letters = length;
4226                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
4227                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4228            }
4229        }
4230    }
4231
4232    @Override
4233    public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
4234        return getStrictestPasswordRequirement(who, userHandle, parent,
4235                admin -> admin.minimumPasswordMetrics.letters, PASSWORD_QUALITY_COMPLEX);
4236    }
4237
4238    @Override
4239    public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
4240        if (!mHasFeature) {
4241            return;
4242        }
4243        Preconditions.checkNotNull(who, "ComponentName is null");
4244        synchronized (this) {
4245            ActiveAdmin ap = getActiveAdminForCallerLocked(
4246                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4247            if (ap.minimumPasswordMetrics.numeric != length) {
4248                ap.minimumPasswordMetrics.numeric = length;
4249                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
4250                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4251            }
4252        }
4253    }
4254
4255    @Override
4256    public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
4257        return getStrictestPasswordRequirement(who, userHandle, parent,
4258                admin -> admin.minimumPasswordMetrics.numeric, PASSWORD_QUALITY_COMPLEX);
4259   }
4260
4261    @Override
4262    public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
4263        if (!mHasFeature) {
4264            return;
4265        }
4266        Preconditions.checkNotNull(who, "ComponentName is null");
4267        synchronized (this) {
4268            ActiveAdmin ap = getActiveAdminForCallerLocked(
4269                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4270            if (ap.minimumPasswordMetrics.symbols != length) {
4271                ap.minimumPasswordMetrics.symbols = length;
4272                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
4273                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4274            }
4275        }
4276    }
4277
4278    @Override
4279    public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
4280        return getStrictestPasswordRequirement(who, userHandle, parent,
4281                admin -> admin.minimumPasswordMetrics.symbols, PASSWORD_QUALITY_COMPLEX);
4282    }
4283
4284    @Override
4285    public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
4286        if (!mHasFeature) {
4287            return;
4288        }
4289        Preconditions.checkNotNull(who, "ComponentName is null");
4290        synchronized (this) {
4291            ActiveAdmin ap = getActiveAdminForCallerLocked(
4292                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4293            if (ap.minimumPasswordMetrics.nonLetter != length) {
4294                ap.minimumPasswordMetrics.nonLetter = length;
4295                updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
4296                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4297            }
4298        }
4299    }
4300
4301    @Override
4302    public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
4303        return getStrictestPasswordRequirement(who, userHandle, parent,
4304                admin -> admin.minimumPasswordMetrics.nonLetter, PASSWORD_QUALITY_COMPLEX);
4305    }
4306
4307    /**
4308     * Calculates strictest (maximum) value for a given password property enforced by admin[s].
4309     */
4310    private int getStrictestPasswordRequirement(ComponentName who, int userHandle,
4311            boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) {
4312        if (!mHasFeature) {
4313            return 0;
4314        }
4315        enforceFullCrossUsersPermission(userHandle);
4316        synchronized (this) {
4317            if (who != null) {
4318                final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4319                return admin != null ? getter.apply(admin) : 0;
4320            }
4321
4322            int maxValue = 0;
4323            final List<ActiveAdmin> admins =
4324                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4325            final int N = admins.size();
4326            for (int i = 0; i < N; i++) {
4327                final ActiveAdmin admin = admins.get(i);
4328                if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) {
4329                    continue;
4330                }
4331                final Integer adminValue = getter.apply(admin);
4332                if (adminValue > maxValue) {
4333                    maxValue = adminValue;
4334                }
4335            }
4336            return maxValue;
4337        }
4338    }
4339
4340    /* @return the password blacklist set by the admin or {@code null} if none. */
4341    PasswordBlacklist getAdminPasswordBlacklistLocked(@NonNull ActiveAdmin admin) {
4342        final int userId = UserHandle.getUserId(admin.getUid());
4343        return admin.passwordBlacklistFile == null ? null : new PasswordBlacklist(
4344                new File(getPolicyFileDirectory(userId), admin.passwordBlacklistFile));
4345    }
4346
4347    private static final String PASSWORD_BLACKLIST_FILE_PREFIX = "password-blacklist-";
4348    private static final String PASSWORD_BLACKLIST_FILE_SUFFIX = "";
4349
4350    @Override
4351    public boolean setPasswordBlacklist(ComponentName who, String name, List<String> blacklist,
4352            boolean parent) {
4353        if (!mHasFeature) {
4354            return false;
4355        }
4356        Preconditions.checkNotNull(who, "who is null");
4357
4358        synchronized (this) {
4359            final ActiveAdmin admin = getActiveAdminForCallerLocked(
4360                    who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4361            final int userId = mInjector.userHandleGetCallingUserId();
4362            PasswordBlacklist adminBlacklist = getAdminPasswordBlacklistLocked(admin);
4363
4364            if (blacklist == null || blacklist.isEmpty()) {
4365                // Remove the adminBlacklist
4366                admin.passwordBlacklistFile = null;
4367                saveSettingsLocked(userId);
4368                if (adminBlacklist != null) {
4369                    adminBlacklist.delete();
4370                }
4371                return true;
4372            }
4373
4374            // Validate server side
4375            Preconditions.checkNotNull(name, "name is null");
4376            DevicePolicyManager.enforcePasswordBlacklistSize(blacklist);
4377
4378            // Blacklist is case insensitive so normalize to lower case
4379            final int blacklistSize = blacklist.size();
4380            for (int i = 0; i < blacklistSize; ++i) {
4381                blacklist.set(i, blacklist.get(i).toLowerCase());
4382            }
4383
4384            final boolean isNewBlacklist = adminBlacklist == null;
4385            if (isNewBlacklist) {
4386                // Create a new file for the blacklist. There could be multiple admins, each setting
4387                // different blacklists, to restrict a user's credential, for example a managed
4388                // profile can impose restrictions on its parent while the parent is already
4389                // restricted by its own admin. A deterministic naming scheme would be fragile if
4390                // new types of admin are introduced so we generate and save the file name instead.
4391                // This isn't a temporary file but it reuses the name generation logic
4392                final File file;
4393                try {
4394                    file = File.createTempFile(PASSWORD_BLACKLIST_FILE_PREFIX,
4395                            PASSWORD_BLACKLIST_FILE_SUFFIX, getPolicyFileDirectory(userId));
4396                } catch (IOException e) {
4397                    Slog.e(LOG_TAG, "Failed to make a file for the blacklist", e);
4398                    return false;
4399                }
4400                adminBlacklist = mInjector.newPasswordBlacklist(file);
4401            }
4402
4403            if (adminBlacklist.savePasswordBlacklist(name, blacklist)) {
4404                if (isNewBlacklist) {
4405                    // The blacklist was saved so point the admin to the file
4406                    admin.passwordBlacklistFile = adminBlacklist.getFile().getName();
4407                    saveSettingsLocked(userId);
4408                }
4409                return true;
4410            }
4411        }
4412
4413        return false;
4414    }
4415
4416    @Override
4417    public String getPasswordBlacklistName(ComponentName who, @UserIdInt int userId,
4418            boolean parent) {
4419        if (!mHasFeature) {
4420            return null;
4421        }
4422        Preconditions.checkNotNull(who, "who is null");
4423        enforceFullCrossUsersPermission(userId);
4424        synchronized (this) {
4425            final ActiveAdmin admin = getActiveAdminForCallerLocked(
4426                    who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4427            final PasswordBlacklist blacklist = getAdminPasswordBlacklistLocked(admin);
4428            if (blacklist == null) {
4429                return null;
4430            }
4431            return blacklist.getName();
4432        }
4433    }
4434
4435    @Override
4436    public boolean isPasswordBlacklisted(@UserIdInt int userId, String password) {
4437        if (!mHasFeature) {
4438            return false;
4439        }
4440        mContext.enforceCallingOrSelfPermission(
4441                android.Manifest.permission.TEST_BLACKLISTED_PASSWORD, null);
4442        return isPasswordBlacklistedInternal(userId, password);
4443    }
4444
4445    private boolean isPasswordBlacklistedInternal(@UserIdInt int userId, String password) {
4446        Preconditions.checkNotNull(password, "Password is null");
4447        enforceFullCrossUsersPermission(userId);
4448
4449        // Normalize to lower case for case insensitive blacklist match
4450        final String lowerCasePassword = password.toLowerCase();
4451
4452        synchronized (this) {
4453            final List<ActiveAdmin> admins =
4454                    getActiveAdminsForLockscreenPoliciesLocked(userId, /* parent */ false);
4455            final int N = admins.size();
4456            for (int i = 0; i < N; i++) {
4457                final PasswordBlacklist blacklist
4458                        = getAdminPasswordBlacklistLocked(admins.get(i));
4459                if (blacklist != null) {
4460                    if (blacklist.isPasswordBlacklisted(lowerCasePassword)) {
4461                        return true;
4462                    }
4463                }
4464            }
4465        }
4466
4467        return false;
4468    }
4469
4470    @Override
4471    public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
4472        if (!mHasFeature) {
4473            return true;
4474        }
4475        enforceFullCrossUsersPermission(userHandle);
4476        enforceUserUnlocked(userHandle, parent);
4477
4478        synchronized (this) {
4479            // This API can only be called by an active device admin,
4480            // so try to retrieve it to check that the caller is one.
4481            getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4482            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4483            return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
4484        }
4485    }
4486
4487    @Override
4488    public boolean isUsingUnifiedPassword(ComponentName admin) {
4489        if (!mHasFeature) {
4490            return true;
4491        }
4492        final int userId = mInjector.userHandleGetCallingUserId();
4493        enforceProfileOrDeviceOwner(admin);
4494        enforceManagedProfile(userId, "query unified challenge status");
4495        return !isSeparateProfileChallengeEnabled(userId);
4496    }
4497
4498    @Override
4499    public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
4500        if (!mHasFeature) {
4501            return true;
4502        }
4503        enforceFullCrossUsersPermission(userHandle);
4504        enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
4505
4506        synchronized (this) {
4507            final int targetUser = getProfileParentId(userHandle);
4508            enforceUserUnlocked(targetUser, false);
4509            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
4510            return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
4511        }
4512    }
4513
4514    private boolean isActivePasswordSufficientForUserLocked(
4515            DevicePolicyData policy, int userHandle, boolean parent) {
4516        final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
4517        if (requiredPasswordQuality == PASSWORD_QUALITY_UNSPECIFIED) {
4518            // A special case is when there is no required password quality, then we just return
4519            // true since any password would be sufficient. This is for the scenario when a work
4520            // profile is first created so there is no information about the current password but
4521            // it should be considered sufficient as there is no password requirement either.
4522            // This is useful since it short-circuits the password checkpoint for FDE device below.
4523            return true;
4524        }
4525
4526        if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
4527                && !policy.mPasswordStateHasBeenSetSinceBoot) {
4528            // Before user enters their password for the first time after a reboot, return the
4529            // value of this flag, which tells us whether the password was valid the last time
4530            // settings were saved.  If DPC changes password requirements on boot so that the
4531            // current password no longer meets the requirements, this value will be stale until
4532            // the next time the password is entered.
4533            return policy.mPasswordValidAtLastCheckpoint;
4534        }
4535
4536        if (policy.mActivePasswordMetrics.quality < requiredPasswordQuality) {
4537            return false;
4538        }
4539        if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
4540                && policy.mActivePasswordMetrics.length < getPasswordMinimumLength(
4541                        null, userHandle, parent)) {
4542            return false;
4543        }
4544        if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4545            return true;
4546        }
4547        return policy.mActivePasswordMetrics.upperCase >= getPasswordMinimumUpperCase(
4548                    null, userHandle, parent)
4549                && policy.mActivePasswordMetrics.lowerCase >= getPasswordMinimumLowerCase(
4550                        null, userHandle, parent)
4551                && policy.mActivePasswordMetrics.letters >= getPasswordMinimumLetters(
4552                        null, userHandle, parent)
4553                && policy.mActivePasswordMetrics.numeric >= getPasswordMinimumNumeric(
4554                        null, userHandle, parent)
4555                && policy.mActivePasswordMetrics.symbols >= getPasswordMinimumSymbols(
4556                        null, userHandle, parent)
4557                && policy.mActivePasswordMetrics.nonLetter >= getPasswordMinimumNonLetter(
4558                        null, userHandle, parent);
4559    }
4560
4561    @Override
4562    public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
4563        enforceFullCrossUsersPermission(userHandle);
4564        synchronized (this) {
4565            if (!isCallerWithSystemUid()) {
4566                // This API can only be called by an active device admin,
4567                // so try to retrieve it to check that the caller is one.
4568                getActiveAdminForCallerLocked(
4569                        null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4570            }
4571
4572            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4573
4574            return policy.mFailedPasswordAttempts;
4575        }
4576    }
4577
4578    @Override
4579    public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
4580        if (!mHasFeature) {
4581            return;
4582        }
4583        Preconditions.checkNotNull(who, "ComponentName is null");
4584        synchronized (this) {
4585            // This API can only be called by an active device admin,
4586            // so try to retrieve it to check that the caller is one.
4587            getActiveAdminForCallerLocked(
4588                    who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
4589            ActiveAdmin ap = getActiveAdminForCallerLocked(
4590                    who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4591            if (ap.maximumFailedPasswordsForWipe != num) {
4592                ap.maximumFailedPasswordsForWipe = num;
4593                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4594            }
4595        }
4596    }
4597
4598    @Override
4599    public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
4600        if (!mHasFeature) {
4601            return 0;
4602        }
4603        enforceFullCrossUsersPermission(userHandle);
4604        synchronized (this) {
4605            ActiveAdmin admin = (who != null)
4606                    ? getActiveAdminUncheckedLocked(who, userHandle, parent)
4607                    : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
4608            return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
4609        }
4610    }
4611
4612    @Override
4613    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
4614        if (!mHasFeature) {
4615            return UserHandle.USER_NULL;
4616        }
4617        enforceFullCrossUsersPermission(userHandle);
4618        synchronized (this) {
4619            ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4620                    userHandle, parent);
4621            return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
4622        }
4623    }
4624
4625    /**
4626     * Returns the admin with the strictest policy on maximum failed passwords for:
4627     * <ul>
4628     *   <li>this user if it has a separate profile challenge, or
4629     *   <li>this user and all profiles that don't have their own challenge otherwise.
4630     * </ul>
4631     * <p>If the policy for the primary and any other profile are equal, it returns the admin for
4632     * the primary profile.
4633     * Returns {@code null} if no participating admin has that policy set.
4634     */
4635    private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
4636            int userHandle, boolean parent) {
4637        int count = 0;
4638        ActiveAdmin strictestAdmin = null;
4639
4640        // Return the strictest policy across all participating admins.
4641        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4642        final int N = admins.size();
4643        for (int i = 0; i < N; i++) {
4644            ActiveAdmin admin = admins.get(i);
4645            if (admin.maximumFailedPasswordsForWipe ==
4646                    ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
4647                continue;  // No max number of failed passwords policy set for this profile.
4648            }
4649
4650            // We always favor the primary profile if several profiles have the same value set.
4651            int userId = admin.getUserHandle().getIdentifier();
4652            if (count == 0 ||
4653                    count > admin.maximumFailedPasswordsForWipe ||
4654                    (count == admin.maximumFailedPasswordsForWipe &&
4655                            getUserInfo(userId).isPrimary())) {
4656                count = admin.maximumFailedPasswordsForWipe;
4657                strictestAdmin = admin;
4658            }
4659        }
4660        return strictestAdmin;
4661    }
4662
4663    private UserInfo getUserInfo(@UserIdInt int userId) {
4664        final long token = mInjector.binderClearCallingIdentity();
4665        try {
4666            return mUserManager.getUserInfo(userId);
4667        } finally {
4668            mInjector.binderRestoreCallingIdentity(token);
4669        }
4670    }
4671
4672    private boolean canPOorDOCallResetPassword(ActiveAdmin admin, @UserIdInt int userId) {
4673        // Only if the admins targets a pre-O SDK
4674        return getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.O;
4675    }
4676
4677    /* PO or DO could do an untrusted reset in certain conditions. */
4678    private boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) {
4679        synchronized (this) {
4680            // An active DO or PO might be able to fo an untrusted credential reset
4681            for (final ActiveAdmin admin : getUserData(userId).mAdminList) {
4682                if (!isActiveAdminWithPolicyForUserLocked(admin,
4683                          DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, userId)) {
4684                    continue;
4685                }
4686                if (canPOorDOCallResetPassword(admin, userId)) {
4687                    return true;
4688                }
4689            }
4690            return false;
4691        }
4692    }
4693
4694    @Override
4695    public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
4696        final int callingUid = mInjector.binderGetCallingUid();
4697        final int userHandle = mInjector.userHandleGetCallingUserId();
4698
4699        String password = passwordOrNull != null ? passwordOrNull : "";
4700
4701        // Password resetting to empty/null is not allowed for managed profiles.
4702        if (TextUtils.isEmpty(password)) {
4703            enforceNotManagedProfile(userHandle, "clear the active password");
4704        }
4705
4706        synchronized (this) {
4707            // If caller has PO (or DO) it can change the password, so see if that's the case first.
4708            ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
4709                    null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
4710            final boolean preN;
4711            if (admin != null) {
4712                if (!canPOorDOCallResetPassword(admin, userHandle)) {
4713                    throw new SecurityException("resetPassword() is deprecated for DPC targeting O"
4714                            + " or later");
4715                }
4716                preN = getTargetSdk(admin.info.getPackageName(),
4717                        userHandle) <= android.os.Build.VERSION_CODES.M;
4718            } else {
4719                // Otherwise, make sure the caller has any active admin with the right policy.
4720                admin = getActiveAdminForCallerLocked(null,
4721                        DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
4722                preN = getTargetSdk(admin.info.getPackageName(),
4723                        userHandle) <= android.os.Build.VERSION_CODES.M;
4724
4725                // As of N, password resetting to empty/null is not allowed anymore.
4726                // TODO Should we allow DO/PO to set an empty password?
4727                if (TextUtils.isEmpty(password)) {
4728                    if (!preN) {
4729                        throw new SecurityException("Cannot call with null password");
4730                    } else {
4731                        Slog.e(LOG_TAG, "Cannot call with null password");
4732                        return false;
4733                    }
4734                }
4735                // As of N, password cannot be changed by the admin if it is already set.
4736                if (isLockScreenSecureUnchecked(userHandle)) {
4737                    if (!preN) {
4738                        throw new SecurityException("Admin cannot change current password");
4739                    } else {
4740                        Slog.e(LOG_TAG, "Admin cannot change current password");
4741                        return false;
4742                    }
4743                }
4744            }
4745            // Do not allow to reset password when current user has a managed profile
4746            if (!isManagedProfile(userHandle)) {
4747                for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4748                    if (userInfo.isManagedProfile()) {
4749                        if (!preN) {
4750                            throw new IllegalStateException(
4751                                    "Cannot reset password on user has managed profile");
4752                        } else {
4753                            Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
4754                            return false;
4755                        }
4756                    }
4757                }
4758            }
4759            // Do not allow to reset password when user is locked
4760            if (!mUserManager.isUserUnlocked(userHandle)) {
4761                if (!preN) {
4762                    throw new IllegalStateException("Cannot reset password when user is locked");
4763                } else {
4764                    Slog.e(LOG_TAG, "Cannot reset password when user is locked");
4765                    return false;
4766                }
4767            }
4768        }
4769
4770        return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle);
4771    }
4772
4773    private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token,
4774            int flags, int callingUid, int userHandle) {
4775        int quality;
4776        synchronized (this) {
4777            quality = getPasswordQuality(null, userHandle, /* parent */ false);
4778            if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
4779                quality = PASSWORD_QUALITY_UNSPECIFIED;
4780            }
4781            final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password);
4782            if (quality != PASSWORD_QUALITY_UNSPECIFIED) {
4783                final int realQuality = metrics.quality;
4784                if (realQuality < quality
4785                        && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4786                    Slog.w(LOG_TAG, "resetPassword: password quality 0x"
4787                            + Integer.toHexString(realQuality)
4788                            + " does not meet required quality 0x"
4789                            + Integer.toHexString(quality));
4790                    return false;
4791                }
4792                quality = Math.max(realQuality, quality);
4793            }
4794            int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
4795            if (password.length() < length) {
4796                Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
4797                        + " does not meet required length " + length);
4798                return false;
4799            }
4800            if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4801                int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4802                if(metrics.letters < neededLetters) {
4803                    Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters
4804                            + " does not meet required number of letters " + neededLetters);
4805                    return false;
4806                }
4807                int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4808                if (metrics.numeric < neededNumeric) {
4809                    Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric
4810                            + " does not meet required number of numerical digits "
4811                            + neededNumeric);
4812                    return false;
4813                }
4814                int neededLowerCase = getPasswordMinimumLowerCase(
4815                        null, userHandle, /* parent */ false);
4816                if (metrics.lowerCase < neededLowerCase) {
4817                    Slog.w(LOG_TAG, "resetPassword: number of lowercase letters "
4818                            + metrics.lowerCase
4819                            + " does not meet required number of lowercase letters "
4820                            + neededLowerCase);
4821                    return false;
4822                }
4823                int neededUpperCase = getPasswordMinimumUpperCase(
4824                        null, userHandle, /* parent */ false);
4825                if (metrics.upperCase < neededUpperCase) {
4826                    Slog.w(LOG_TAG, "resetPassword: number of uppercase letters "
4827                            + metrics.upperCase
4828                            + " does not meet required number of uppercase letters "
4829                            + neededUpperCase);
4830                    return false;
4831                }
4832                int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4833                if (metrics.symbols < neededSymbols) {
4834                    Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols
4835                            + " does not meet required number of special symbols " + neededSymbols);
4836                    return false;
4837                }
4838                int neededNonLetter = getPasswordMinimumNonLetter(
4839                        null, userHandle, /* parent */ false);
4840                if (metrics.nonLetter < neededNonLetter) {
4841                    Slog.w(LOG_TAG, "resetPassword: number of non-letter characters "
4842                            + metrics.nonLetter
4843                            + " does not meet required number of non-letter characters "
4844                            + neededNonLetter);
4845                    return false;
4846                }
4847            }
4848
4849            if (isPasswordBlacklistedInternal(userHandle, password)) {
4850                Slog.w(LOG_TAG, "resetPassword: the password is blacklisted");
4851                return false;
4852            }
4853        }
4854
4855        DevicePolicyData policy = getUserData(userHandle);
4856        if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4857            Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4858            return false;
4859        }
4860
4861        boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4862        boolean doNotAskCredentialsOnBoot =
4863                (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4864        if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4865            setDoNotAskCredentialsOnBoot();
4866        }
4867
4868        // Don't do this with the lock held, because it is going to call
4869        // back in to the service.
4870        final long ident = mInjector.binderClearCallingIdentity();
4871        final boolean result;
4872        try {
4873            if (token == null) {
4874                if (!TextUtils.isEmpty(password)) {
4875                    mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4876                } else {
4877                    mLockPatternUtils.clearLock(null, userHandle);
4878                }
4879                result = true;
4880            } else {
4881                result = mLockPatternUtils.setLockCredentialWithToken(password,
4882                        TextUtils.isEmpty(password) ? LockPatternUtils.CREDENTIAL_TYPE_NONE
4883                                : LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
4884                                quality, tokenHandle, token, userHandle);
4885            }
4886            boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4887            if (requireEntry) {
4888                mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4889                        UserHandle.USER_ALL);
4890            }
4891            synchronized (this) {
4892                int newOwner = requireEntry ? callingUid : -1;
4893                if (policy.mPasswordOwner != newOwner) {
4894                    policy.mPasswordOwner = newOwner;
4895                    saveSettingsLocked(userHandle);
4896                }
4897            }
4898        } finally {
4899            mInjector.binderRestoreCallingIdentity(ident);
4900        }
4901        return result;
4902    }
4903
4904    private boolean isLockScreenSecureUnchecked(int userId) {
4905        long ident = mInjector.binderClearCallingIdentity();
4906        try {
4907            return mLockPatternUtils.isSecure(userId);
4908        } finally {
4909            mInjector.binderRestoreCallingIdentity(ident);
4910        }
4911    }
4912
4913    private void setDoNotAskCredentialsOnBoot() {
4914        synchronized (this) {
4915            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4916            if (!policyData.doNotAskCredentialsOnBoot) {
4917                policyData.doNotAskCredentialsOnBoot = true;
4918                saveSettingsLocked(UserHandle.USER_SYSTEM);
4919            }
4920        }
4921    }
4922
4923    @Override
4924    public boolean getDoNotAskCredentialsOnBoot() {
4925        mContext.enforceCallingOrSelfPermission(
4926                android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4927        synchronized (this) {
4928            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4929            return policyData.doNotAskCredentialsOnBoot;
4930        }
4931    }
4932
4933    @Override
4934    public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4935        if (!mHasFeature) {
4936            return;
4937        }
4938        Preconditions.checkNotNull(who, "ComponentName is null");
4939        final int userHandle = mInjector.userHandleGetCallingUserId();
4940        synchronized (this) {
4941            ActiveAdmin ap = getActiveAdminForCallerLocked(
4942                    who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4943            if (ap.maximumTimeToUnlock != timeMs) {
4944                ap.maximumTimeToUnlock = timeMs;
4945                saveSettingsLocked(userHandle);
4946                updateMaximumTimeToLockLocked(userHandle);
4947            }
4948        }
4949    }
4950
4951    private void updateMaximumTimeToLockLocked(@UserIdInt int userId) {
4952        // Update the profile's timeout
4953        if (isManagedProfile(userId)) {
4954            updateProfileLockTimeoutLocked(userId);
4955        }
4956
4957        final long timeMs;
4958        final long ident = mInjector.binderClearCallingIdentity();
4959        try {
4960            // Update the device timeout
4961            final int parentId = getProfileParentId(userId);
4962            timeMs = getMaximumTimeToLockPolicyFromAdmins(
4963                    getActiveAdminsForLockscreenPoliciesLocked(parentId, false));
4964
4965            final DevicePolicyData policy = getUserDataUnchecked(parentId);
4966            if (policy.mLastMaximumTimeToLock == timeMs) {
4967                return;
4968            }
4969            policy.mLastMaximumTimeToLock = timeMs;
4970
4971            if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4972                // Make sure KEEP_SCREEN_ON is disabled, since that
4973                // would allow bypassing of the maximum time to lock.
4974                mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4975            }
4976        } finally {
4977            mInjector.binderRestoreCallingIdentity(ident);
4978        }
4979
4980        mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4981                UserHandle.USER_SYSTEM, timeMs);
4982    }
4983
4984    private void updateProfileLockTimeoutLocked(@UserIdInt int userId) {
4985        final long timeMs;
4986        if (isSeparateProfileChallengeEnabled(userId)) {
4987            timeMs = getMaximumTimeToLockPolicyFromAdmins(
4988                    getActiveAdminsForLockscreenPoliciesLocked(userId, false /* parent */));
4989        } else {
4990            timeMs = Long.MAX_VALUE;
4991        }
4992
4993        final DevicePolicyData policy = getUserDataUnchecked(userId);
4994        if (policy.mLastMaximumTimeToLock == timeMs) {
4995            return;
4996        }
4997        policy.mLastMaximumTimeToLock = timeMs;
4998
4999        mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
5000                userId, policy.mLastMaximumTimeToLock);
5001    }
5002
5003    @Override
5004    public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
5005        if (!mHasFeature) {
5006            return 0;
5007        }
5008        enforceFullCrossUsersPermission(userHandle);
5009        synchronized (this) {
5010            if (who != null) {
5011                final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5012                return admin != null ? admin.maximumTimeToUnlock : 0;
5013            }
5014            // Return the strictest policy across all participating admins.
5015            final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5016                    userHandle, parent);
5017            final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins);
5018            return timeMs == Long.MAX_VALUE ? 0 : timeMs;
5019        }
5020    }
5021
5022    private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
5023        long time = Long.MAX_VALUE;
5024        for (final ActiveAdmin admin : admins) {
5025            if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) {
5026                time = admin.maximumTimeToUnlock;
5027            }
5028        }
5029        return time;
5030    }
5031
5032    @Override
5033    public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
5034            boolean parent) {
5035        if (!mHasFeature) {
5036            return;
5037        }
5038        Preconditions.checkNotNull(who, "ComponentName is null");
5039        Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
5040        // timeoutMs with value 0 means that the admin doesn't participate
5041        // timeoutMs is clamped to the interval in case the internal constants change in the future
5042        final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
5043        if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
5044            timeoutMs = minimumStrongAuthTimeout;
5045        }
5046        if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
5047            timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5048        }
5049
5050        final int userHandle = mInjector.userHandleGetCallingUserId();
5051        synchronized (this) {
5052            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5053                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
5054            if (ap.strongAuthUnlockTimeout != timeoutMs) {
5055                ap.strongAuthUnlockTimeout = timeoutMs;
5056                saveSettingsLocked(userHandle);
5057            }
5058        }
5059    }
5060
5061    /**
5062     * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
5063     * admins if who is null.
5064     * Returns 0 if not configured for the provided admin.
5065     */
5066    @Override
5067    public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
5068        if (!mHasFeature) {
5069            return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5070        }
5071        enforceFullCrossUsersPermission(userId);
5072        synchronized (this) {
5073            if (who != null) {
5074                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
5075                return admin != null ? admin.strongAuthUnlockTimeout : 0;
5076            }
5077
5078            // Return the strictest policy across all participating admins.
5079            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
5080
5081            long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5082            for (int i = 0; i < admins.size(); i++) {
5083                final long timeout = admins.get(i).strongAuthUnlockTimeout;
5084                if (timeout != 0) { // take only participating admins into account
5085                    strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
5086                }
5087            }
5088            return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
5089        }
5090    }
5091
5092    private long getMinimumStrongAuthTimeoutMs() {
5093        if (!mInjector.isBuildDebuggable()) {
5094            return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
5095        }
5096        // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
5097        // name cannot be longer than 31 characters
5098        return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
5099                MINIMUM_STRONG_AUTH_TIMEOUT_MS),
5100                MINIMUM_STRONG_AUTH_TIMEOUT_MS);
5101    }
5102
5103    @Override
5104    public void lockNow(int flags, boolean parent) {
5105        if (!mHasFeature) {
5106            return;
5107        }
5108
5109        final int callingUserId = mInjector.userHandleGetCallingUserId();
5110        synchronized (this) {
5111            // This API can only be called by an active device admin,
5112            // so try to retrieve it to check that the caller is one.
5113            final ActiveAdmin admin = getActiveAdminForCallerLocked(
5114                    null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
5115
5116            final long ident = mInjector.binderClearCallingIdentity();
5117            try {
5118                // Evict key
5119                if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
5120                    enforceManagedProfile(
5121                            callingUserId, "set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
5122                    if (!isProfileOwner(admin.info.getComponent(), callingUserId)) {
5123                        throw new SecurityException("Only profile owner admins can set "
5124                                + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
5125                    }
5126                    if (parent) {
5127                        throw new IllegalArgumentException(
5128                                "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent");
5129                    }
5130                    if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5131                        throw new UnsupportedOperationException(
5132                                "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices");
5133                    }
5134                    mUserManager.evictCredentialEncryptionKey(callingUserId);
5135                }
5136
5137                // Lock all users unless this is a managed profile with a separate challenge
5138                final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
5139                        ? UserHandle.USER_ALL : callingUserId);
5140                mLockPatternUtils.requireStrongAuth(
5141                        STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
5142
5143                // Require authentication for the device or profile
5144                if (userToLock == UserHandle.USER_ALL) {
5145                    // Power off the display
5146                    mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
5147                            PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
5148                    mInjector.getIWindowManager().lockNow(null);
5149                } else {
5150                    mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
5151                }
5152            } catch (RemoteException e) {
5153            } finally {
5154                mInjector.binderRestoreCallingIdentity(ident);
5155            }
5156        }
5157    }
5158
5159    @Override
5160    public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
5161        if (who == null) {
5162            if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) {
5163                mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
5164            }
5165        } else {
5166            enforceProfileOrDeviceOwner(who);
5167        }
5168    }
5169
5170    private void enforceProfileOrDeviceOwner(ComponentName who) {
5171        synchronized (this) {
5172            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5173        }
5174    }
5175
5176    @Override
5177    public boolean approveCaCert(String alias, int userId, boolean approval) {
5178        enforceManageUsers();
5179        synchronized (this) {
5180            Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
5181            boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
5182            if (!changed) {
5183                return false;
5184            }
5185            saveSettingsLocked(userId);
5186        }
5187        mCertificateMonitor.onCertificateApprovalsChanged(userId);
5188        return true;
5189    }
5190
5191    @Override
5192    public boolean isCaCertApproved(String alias, int userId) {
5193        enforceManageUsers();
5194        synchronized (this) {
5195            return getUserData(userId).mAcceptedCaCertificates.contains(alias);
5196        }
5197    }
5198
5199    private void removeCaApprovalsIfNeeded(int userId) {
5200        for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
5201            boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
5202            if (userInfo.isManagedProfile()){
5203                isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
5204            }
5205            if (!isSecure) {
5206                synchronized (this) {
5207                    getUserData(userInfo.id).mAcceptedCaCertificates.clear();
5208                    saveSettingsLocked(userInfo.id);
5209                }
5210                mCertificateMonitor.onCertificateApprovalsChanged(userId);
5211            }
5212        }
5213    }
5214
5215    @Override
5216    public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)
5217            throws RemoteException {
5218        if (!mHasFeature) {
5219            return false;
5220        }
5221        enforceCanManageCaCerts(admin, callerPackage);
5222
5223        final String alias;
5224
5225        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
5226        final long id = mInjector.binderClearCallingIdentity();
5227        try {
5228            alias = mCertificateMonitor.installCaCert(userHandle, certBuffer);
5229            if (alias == null) {
5230                Log.w(LOG_TAG, "Problem installing cert");
5231                return false;
5232            }
5233        } finally {
5234            mInjector.binderRestoreCallingIdentity(id);
5235        }
5236
5237        synchronized (this) {
5238            getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias);
5239            saveSettingsLocked(userHandle.getIdentifier());
5240        }
5241        return true;
5242    }
5243
5244    @Override
5245    public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
5246        if (!mHasFeature) {
5247            return;
5248        }
5249        enforceCanManageCaCerts(admin, callerPackage);
5250
5251        final int userId = mInjector.userHandleGetCallingUserId();
5252        final long id = mInjector.binderClearCallingIdentity();
5253        try {
5254            mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases);
5255        } finally {
5256            mInjector.binderRestoreCallingIdentity(id);
5257        }
5258
5259        synchronized (this) {
5260            if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) {
5261                saveSettingsLocked(userId);
5262            }
5263        }
5264    }
5265
5266    @Override
5267    public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
5268            byte[] cert, byte[] chain, String alias, boolean requestAccess,
5269            boolean isUserSelectable) {
5270        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5271                DELEGATION_CERT_INSTALL);
5272
5273
5274        final int callingUid = mInjector.binderGetCallingUid();
5275        final long id = mInjector.binderClearCallingIdentity();
5276        try {
5277            final KeyChainConnection keyChainConnection =
5278                    KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
5279            try {
5280                IKeyChainService keyChain = keyChainConnection.getService();
5281                if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
5282                    return false;
5283                }
5284                if (requestAccess) {
5285                    keyChain.setGrant(callingUid, alias, true);
5286                }
5287                keyChain.setUserSelectable(alias, isUserSelectable);
5288                return true;
5289            } catch (RemoteException e) {
5290                Log.e(LOG_TAG, "Installing certificate", e);
5291            } finally {
5292                keyChainConnection.close();
5293            }
5294        } catch (InterruptedException e) {
5295            Log.w(LOG_TAG, "Interrupted while installing certificate", e);
5296            Thread.currentThread().interrupt();
5297        } finally {
5298            mInjector.binderRestoreCallingIdentity(id);
5299        }
5300        return false;
5301    }
5302
5303    @Override
5304    public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
5305        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5306                DELEGATION_CERT_INSTALL);
5307
5308        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
5309        final long id = Binder.clearCallingIdentity();
5310        try {
5311            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
5312            try {
5313                IKeyChainService keyChain = keyChainConnection.getService();
5314                return keyChain.removeKeyPair(alias);
5315            } catch (RemoteException e) {
5316                Log.e(LOG_TAG, "Removing keypair", e);
5317            } finally {
5318                keyChainConnection.close();
5319            }
5320        } catch (InterruptedException e) {
5321            Log.w(LOG_TAG, "Interrupted while removing keypair", e);
5322            Thread.currentThread().interrupt();
5323        } finally {
5324            Binder.restoreCallingIdentity(id);
5325        }
5326        return false;
5327    }
5328
5329    private void enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner(
5330            ComponentName who, String callerPackage, int callerUid) throws SecurityException {
5331        if (who == null) {
5332            if (!mOwners.hasDeviceOwner()) {
5333                throw new SecurityException("Not in Device Owner mode.");
5334            }
5335            if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
5336                throw new SecurityException("Caller not from device owner user");
5337            }
5338            if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) {
5339                throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid() +
5340                        "has no permission to generate keys.");
5341            }
5342        } else {
5343            // Caller provided - check it is the device owner.
5344            synchronized (this) {
5345                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5346            }
5347        }
5348    }
5349
5350    @VisibleForTesting
5351    public static int[] translateIdAttestationFlags(
5352            int idAttestationFlags) {
5353        Map<Integer, Integer> idTypeToAttestationFlag = new HashMap();
5354        idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL);
5355        idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI);
5356        idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID);
5357
5358        int numFlagsSet = Integer.bitCount(idAttestationFlags);
5359        // No flags are set - return null to indicate no device ID attestation information should
5360        // be included in the attestation record.
5361        if (numFlagsSet == 0) {
5362            return null;
5363        }
5364
5365        // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if
5366        // no other flag is set. That will lead to inclusion of general device make data in the
5367        // attestation record, but no specific device identifiers.
5368        if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) {
5369            numFlagsSet -= 1;
5370            idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO);
5371        }
5372
5373        int[] attestationUtilsFlags = new int[numFlagsSet];
5374        int i = 0;
5375        for (Integer idType: idTypeToAttestationFlag.keySet()) {
5376            if ((idType & idAttestationFlags) != 0) {
5377                attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType);
5378            }
5379        }
5380
5381        return attestationUtilsFlags;
5382    }
5383
5384    @Override
5385    public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm,
5386            ParcelableKeyGenParameterSpec parcelableKeySpec,
5387            int idAttestationFlags,
5388            KeymasterCertificateChain attestationChain) {
5389        // Get attestation flags, if any.
5390        final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags);
5391        final boolean deviceIdAttestationRequired = attestationUtilsFlags != null;
5392        final int callingUid = mInjector.binderGetCallingUid();
5393
5394        if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) {
5395            enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner(who, callerPackage, callingUid);
5396        } else {
5397            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5398                    DELEGATION_CERT_INSTALL);
5399        }
5400        final KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec();
5401        final String alias = keySpec.getKeystoreAlias();
5402        if (TextUtils.isEmpty(alias)) {
5403            throw new IllegalArgumentException("Empty alias provided.");
5404        }
5405        // As the caller will be granted access to the key, ensure no UID was specified, as
5406        // it will not have the desired effect.
5407        if (keySpec.getUid() != KeyStore.UID_SELF) {
5408            Log.e(LOG_TAG, "Only the caller can be granted access to the generated keypair.");
5409            return false;
5410        }
5411
5412        if (deviceIdAttestationRequired && (keySpec.getAttestationChallenge() == null)) {
5413            throw new IllegalArgumentException(
5414                    "Requested Device ID attestation but challenge is empty.");
5415        }
5416
5417        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
5418        final long id = mInjector.binderClearCallingIdentity();
5419        try {
5420            try (KeyChainConnection keyChainConnection =
5421                    KeyChain.bindAsUser(mContext, userHandle)) {
5422                IKeyChainService keyChain = keyChainConnection.getService();
5423
5424                // Copy the provided keySpec, excluding the attestation challenge, which will be
5425                // used later for requesting key attestation record.
5426                final KeyGenParameterSpec noAttestationSpec =
5427                    new KeyGenParameterSpec.Builder(keySpec)
5428                        .setAttestationChallenge(null)
5429                        .build();
5430
5431                final boolean generationResult = keyChain.generateKeyPair(algorithm,
5432                    new ParcelableKeyGenParameterSpec(noAttestationSpec));
5433                if (!generationResult) {
5434                    Log.e(LOG_TAG, "KeyChain failed to generate a keypair.");
5435                    return false;
5436                }
5437
5438                // Set a grant for the caller here so that when the client calls
5439                // requestPrivateKey, it will be able to get the key from Keystore.
5440                // Note the use of the calling  UID, since the request for the private
5441                // key will come from the client's process, so the grant has to be for
5442                // that UID.
5443                keyChain.setGrant(callingUid, alias, true);
5444
5445                final byte[] attestationChallenge = keySpec.getAttestationChallenge();
5446                if (attestationChallenge != null) {
5447                    final boolean attestationResult = keyChain.attestKey(
5448                            alias, attestationChallenge, attestationUtilsFlags, attestationChain);
5449                    if (!attestationResult) {
5450                        Log.e(LOG_TAG, String.format(
5451                                "Attestation for %s failed, deleting key.", alias));
5452                        keyChain.removeKeyPair(alias);
5453                        return false;
5454                    }
5455                }
5456                return true;
5457            }
5458        } catch (RemoteException e) {
5459            Log.e(LOG_TAG, "KeyChain error while generating a keypair", e);
5460        } catch (InterruptedException e) {
5461            Log.w(LOG_TAG, "Interrupted while generating keypair", e);
5462            Thread.currentThread().interrupt();
5463        } finally {
5464            mInjector.binderRestoreCallingIdentity(id);
5465        }
5466        return false;
5467    }
5468
5469    @Override
5470    public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias,
5471            byte[] cert, byte[] chain, boolean isUserSelectable) {
5472        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5473                DELEGATION_CERT_INSTALL);
5474
5475        final int callingUid = mInjector.binderGetCallingUid();
5476        final long id = mInjector.binderClearCallingIdentity();
5477        try (final KeyChainConnection keyChainConnection =
5478                KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid))) {
5479            IKeyChainService keyChain = keyChainConnection.getService();
5480            if (!keyChain.setKeyPairCertificate(alias, cert, chain)) {
5481                return false;
5482            }
5483            keyChain.setUserSelectable(alias, isUserSelectable);
5484            return true;
5485        } catch (InterruptedException e) {
5486            Log.w(LOG_TAG, "Interrupted while setting keypair certificate", e);
5487            Thread.currentThread().interrupt();
5488        } catch (RemoteException e) {
5489            Log.e(LOG_TAG, "Failed setting keypair certificate", e);
5490        } finally {
5491            mInjector.binderRestoreCallingIdentity(id);
5492        }
5493        return false;
5494    }
5495
5496    @Override
5497    public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
5498            final IBinder response) {
5499        // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
5500        if (!isCallerWithSystemUid()) {
5501            return;
5502        }
5503
5504        final UserHandle caller = mInjector.binderGetCallingUserHandle();
5505        // If there is a profile owner, redirect to that; otherwise query the device owner.
5506        ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
5507        if (aliasChooser == null && caller.isSystem()) {
5508            ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
5509            if (deviceOwnerAdmin != null) {
5510                aliasChooser = deviceOwnerAdmin.info.getComponent();
5511            }
5512        }
5513        if (aliasChooser == null) {
5514            sendPrivateKeyAliasResponse(null, response);
5515            return;
5516        }
5517
5518        Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
5519        intent.setComponent(aliasChooser);
5520        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
5521        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
5522        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
5523        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
5524        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
5525
5526        final long id = mInjector.binderClearCallingIdentity();
5527        try {
5528            mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
5529                @Override
5530                public void onReceive(Context context, Intent intent) {
5531                    final String chosenAlias = getResultData();
5532                    sendPrivateKeyAliasResponse(chosenAlias, response);
5533                }
5534            }, null, Activity.RESULT_OK, null, null);
5535        } finally {
5536            mInjector.binderRestoreCallingIdentity(id);
5537        }
5538    }
5539
5540    private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
5541        final IKeyChainAliasCallback keyChainAliasResponse =
5542                IKeyChainAliasCallback.Stub.asInterface(responseBinder);
5543        // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback
5544        // is oneway, which means it won't block if the recipient lives in another process.
5545        try {
5546            keyChainAliasResponse.alias(alias);
5547        } catch (Exception e) {
5548            // Caller could throw RuntimeException or RemoteException back across processes. Catch
5549            // everything just to be sure.
5550            Log.e(LOG_TAG, "error while responding to callback", e);
5551        }
5552    }
5553
5554    /**
5555     * Determine whether DPMS should check if a delegate package is already installed before
5556     * granting it new delegations via {@link #setDelegatedScopes}.
5557     */
5558    private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage,
5559            int targetSdk, List<String> scopes) {
5560        // 1) Never skip is installed check from N.
5561        if (targetSdk >= Build.VERSION_CODES.N) {
5562            return true;
5563        }
5564        // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given.
5565        if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) {
5566            return false;
5567        }
5568        // 3) Skip if all previously granted scopes are being cleared.
5569        if (scopes.isEmpty()) {
5570            return false;
5571        }
5572        // Otherwise it should check that delegatePackage is installed.
5573        return true;
5574    }
5575
5576    /**
5577     * Set the scopes of a device owner or profile owner delegate.
5578     *
5579     * @param who the device owner or profile owner.
5580     * @param delegatePackage the name of the delegate package.
5581     * @param scopes the list of delegation scopes to be given to the delegate package.
5582     */
5583    @Override
5584    public void setDelegatedScopes(ComponentName who, String delegatePackage,
5585            List<String> scopes) throws SecurityException {
5586        Preconditions.checkNotNull(who, "ComponentName is null");
5587        Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
5588        Preconditions.checkCollectionElementsNotNull(scopes, "Scopes");
5589        // Remove possible duplicates.
5590        scopes = new ArrayList(new ArraySet(scopes));
5591        // Ensure given scopes are valid.
5592        if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
5593            throw new IllegalArgumentException("Unexpected delegation scopes");
5594        }
5595
5596        // Retrieve the user ID of the calling process.
5597        final int userId = mInjector.userHandleGetCallingUserId();
5598        synchronized (this) {
5599            // Ensure calling process is device/profile owner.
5600            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5601            // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
5602            if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage,
5603                        getTargetSdk(who.getPackageName(), userId), scopes)) {
5604                // Throw when the delegate package is not installed.
5605                if (!isPackageInstalledForUser(delegatePackage, userId)) {
5606                    throw new IllegalArgumentException("Package " + delegatePackage
5607                            + " is not installed on the current user");
5608                }
5609            }
5610
5611            // Set the new delegate in user policies.
5612            final DevicePolicyData policy = getUserData(userId);
5613            if (!scopes.isEmpty()) {
5614                policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
5615            } else {
5616                // Remove any delegation info if the given scopes list is empty.
5617                policy.mDelegationMap.remove(delegatePackage);
5618            }
5619
5620            // Notify delegate package of updates.
5621            final Intent intent = new Intent(
5622                    DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
5623            // Only call receivers registered with Context#registerReceiver (don’t wake delegate).
5624            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
5625            // Limit components this intent resolves to to the delegate package.
5626            intent.setPackage(delegatePackage);
5627            // Include the list of delegated scopes as an extra.
5628            intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES,
5629                    (ArrayList<String>) scopes);
5630            // Send the broadcast.
5631            mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
5632
5633            // Persist updates.
5634            saveSettingsLocked(userId);
5635        }
5636    }
5637
5638    /**
5639     * Get the delegation scopes given to a delegate package by a device owner or profile owner.
5640     *
5641     * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
5642     * passing in {@code null} as the {@code who} parameter and its own name as the
5643     * {@code delegatepackage}.
5644     *
5645     * @param who the device owner or profile owner, or {@code null} if the caller is
5646     *            {@code delegatePackage}.
5647     * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
5648     * @return a list of the delegation scopes currently given to {@code delegatePackage}.
5649     */
5650    @Override
5651    @NonNull
5652    public List<String> getDelegatedScopes(ComponentName who,
5653            String delegatePackage) throws SecurityException {
5654        Preconditions.checkNotNull(delegatePackage, "Delegate package is null");
5655
5656        // Retrieve the user ID of the calling process.
5657        final int callingUid = mInjector.binderGetCallingUid();
5658        final int userId = UserHandle.getUserId(callingUid);
5659        synchronized (this) {
5660            // Ensure calling process is device/profile owner.
5661            if (who != null) {
5662                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5663            // Or ensure calling process is delegatePackage itself.
5664            } else {
5665                int uid = 0;
5666                try {
5667                  uid = mInjector.getPackageManager()
5668                          .getPackageUidAsUser(delegatePackage, userId);
5669                } catch(NameNotFoundException e) {
5670                }
5671                if (uid != callingUid) {
5672                    throw new SecurityException("Caller with uid " + callingUid + " is not "
5673                            + delegatePackage);
5674                }
5675            }
5676            final DevicePolicyData policy = getUserData(userId);
5677            // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
5678            final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5679            return scopes == null ? Collections.EMPTY_LIST : scopes;
5680        }
5681    }
5682
5683    /**
5684     * Get a list of  packages that were given a specific delegation scopes by a device owner or
5685     * profile owner.
5686     *
5687     * @param who the device owner or profile owner.
5688     * @param scope the scope whose delegates are to be retrieved.
5689     * @return a list of the delegate packages currently given the {@code scope} delegation.
5690     */
5691    @NonNull
5692    public List<String> getDelegatePackages(ComponentName who, String scope)
5693            throws SecurityException {
5694        Preconditions.checkNotNull(who, "ComponentName is null");
5695        Preconditions.checkNotNull(scope, "Scope is null");
5696        if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5697            throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5698        }
5699
5700        // Retrieve the user ID of the calling process.
5701        final int userId = mInjector.userHandleGetCallingUserId();
5702        synchronized (this) {
5703            // Ensure calling process is device/profile owner.
5704            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5705            final DevicePolicyData policy = getUserData(userId);
5706
5707            // Create a list to hold the resulting delegate packages.
5708            final List<String> delegatePackagesWithScope = new ArrayList<>();
5709            // Add all delegations containing scope to the result list.
5710            for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5711                if (policy.mDelegationMap.valueAt(i).contains(scope)) {
5712                    delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
5713                }
5714            }
5715            return delegatePackagesWithScope;
5716        }
5717    }
5718
5719    /**
5720     * Check whether a caller application has been delegated a given scope via
5721     * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
5722     * device owner.
5723     * <p>
5724     * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
5725     * then comparing the calling UID with the UID of {@code callerPackage} as reported by
5726     * {@link PackageManager#getPackageUidAsUser}.
5727     *
5728     * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
5729     * @param scope the delegation scope to be checked.
5730     * @return {@code true} if the calling process is a delegate of {@code scope}.
5731     */
5732    private boolean isCallerDelegate(String callerPackage, String scope) {
5733        Preconditions.checkNotNull(callerPackage, "callerPackage is null");
5734        if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5735            throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5736        }
5737
5738        // Retrieve the UID and user ID of the calling process.
5739        final int callingUid = mInjector.binderGetCallingUid();
5740        final int userId = UserHandle.getUserId(callingUid);
5741        synchronized (this) {
5742            // Retrieve user policy data.
5743            final DevicePolicyData policy = getUserData(userId);
5744            // Retrieve the list of delegation scopes granted to callerPackage.
5745            final List<String> scopes = policy.mDelegationMap.get(callerPackage);
5746            // Check callingUid only if callerPackage has the required scope delegation.
5747            if (scopes != null && scopes.contains(scope)) {
5748                try {
5749                    // Retrieve the expected UID for callerPackage.
5750                    final int uid = mInjector.getPackageManager()
5751                            .getPackageUidAsUser(callerPackage, userId);
5752                    // Return true if the caller is actually callerPackage.
5753                    return uid == callingUid;
5754                } catch (NameNotFoundException e) {
5755                    // Ignore.
5756                }
5757            }
5758            return false;
5759        }
5760    }
5761
5762    /**
5763     * Throw a security exception if a ComponentName is given and it is not a device/profile owner
5764     * or if the calling process is not a delegate of the given scope.
5765     *
5766     * @param who the device owner of profile owner, or null if {@code callerPackage} is a
5767     *            {@code scope} delegate.
5768     * @param callerPackage the name of the calling package. Required if {@code who} is
5769     *            {@code null}.
5770     * @param reqPolicy the policy used in the API whose access permission is being checked.
5771     * @param scope the delegation scope corresponding to the API being checked.
5772     * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy};
5773     *            or when {@code who} is {@code null} and {@code callerPackage} is not a delegate
5774     *            of {@code scope}.
5775     */
5776    private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy,
5777            String scope) {
5778        // If a ComponentName is given ensure it is a device or profile owner according to policy.
5779        if (who != null) {
5780            synchronized (this) {
5781                getActiveAdminForCallerLocked(who, reqPolicy);
5782            }
5783        // If no ComponentName is given ensure calling process has scope delegation.
5784        } else if (!isCallerDelegate(callerPackage, scope)) {
5785            throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid()
5786                    + " is not a delegate of scope " + scope + ".");
5787        }
5788    }
5789
5790    /**
5791     * Helper function to preserve delegation behavior pre-O when using the deprecated functions
5792     * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
5793     */
5794    private void setDelegatedScopePreO(ComponentName who,
5795            String delegatePackage, String scope) {
5796        Preconditions.checkNotNull(who, "ComponentName is null");
5797
5798        final int userId = mInjector.userHandleGetCallingUserId();
5799        synchronized(this) {
5800            // Ensure calling process is device/profile owner.
5801            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5802            final DevicePolicyData policy = getUserData(userId);
5803
5804            if (delegatePackage != null) {
5805                // Set package as a delegate for scope if it is not already one.
5806                List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5807                if (scopes == null) {
5808                    scopes = new ArrayList<>();
5809                }
5810                if (!scopes.contains(scope)) {
5811                    scopes.add(scope);
5812                    setDelegatedScopes(who, delegatePackage, scopes);
5813                }
5814            }
5815
5816            // Clear any existing scope delegates.
5817            for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5818                final String currentPackage = policy.mDelegationMap.keyAt(i);
5819                final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
5820
5821                if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) {
5822                    final List<String> newScopes = new ArrayList(currentScopes);
5823                    newScopes.remove(scope);
5824                    setDelegatedScopes(who, currentPackage, newScopes);
5825                }
5826            }
5827        }
5828    }
5829
5830    @Override
5831    public void setCertInstallerPackage(ComponentName who, String installerPackage)
5832            throws SecurityException {
5833        setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
5834    }
5835
5836    @Override
5837    public String getCertInstallerPackage(ComponentName who) throws SecurityException {
5838        final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
5839        return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
5840    }
5841
5842    /**
5843     * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
5844     * not installed and therefore not available.
5845     *
5846     * @throws SecurityException if the caller is not a profile or device owner.
5847     * @throws UnsupportedOperationException if the package does not support being set as always-on.
5848     */
5849    @Override
5850    public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
5851            throws SecurityException {
5852        enforceProfileOrDeviceOwner(admin);
5853
5854        final int userId = mInjector.userHandleGetCallingUserId();
5855        final long token = mInjector.binderClearCallingIdentity();
5856        try {
5857            if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
5858                return false;
5859            }
5860            ConnectivityManager connectivityManager = (ConnectivityManager)
5861                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5862            if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
5863                throw new UnsupportedOperationException();
5864            }
5865        } finally {
5866            mInjector.binderRestoreCallingIdentity(token);
5867        }
5868        return true;
5869    }
5870
5871    @Override
5872    public String getAlwaysOnVpnPackage(ComponentName admin)
5873            throws SecurityException {
5874        enforceProfileOrDeviceOwner(admin);
5875
5876        final int userId = mInjector.userHandleGetCallingUserId();
5877        final long token = mInjector.binderClearCallingIdentity();
5878        try{
5879            ConnectivityManager connectivityManager = (ConnectivityManager)
5880                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5881            return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
5882        } finally {
5883            mInjector.binderRestoreCallingIdentity(token);
5884        }
5885    }
5886
5887    private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc) {
5888        wtfIfInLock();
5889
5890        if (wipeExtRequested) {
5891            StorageManager sm = (StorageManager) mContext.getSystemService(
5892                    Context.STORAGE_SERVICE);
5893            sm.wipeAdoptableDisks();
5894        }
5895        try {
5896            mInjector.recoverySystemRebootWipeUserData(
5897                    /*shutdown=*/ false, reason, /*force=*/ true, /*wipeEuicc=*/ wipeEuicc);
5898        } catch (IOException | SecurityException e) {
5899            Slog.w(LOG_TAG, "Failed requesting data wipe", e);
5900        }
5901    }
5902
5903    private void forceWipeUser(int userId, String wipeReasonForUser) {
5904        try {
5905            IActivityManager am = mInjector.getIActivityManager();
5906            if (am.getCurrentUser().id == userId) {
5907                am.switchUser(UserHandle.USER_SYSTEM);
5908            }
5909
5910            boolean userRemoved = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
5911            if (!userRemoved) {
5912                Slog.w(LOG_TAG, "Couldn't remove user " + userId);
5913            } else if (isManagedProfile(userId)) {
5914                sendWipeProfileNotification(wipeReasonForUser);
5915            }
5916        } catch (RemoteException re) {
5917            // Shouldn't happen
5918        }
5919    }
5920
5921    @Override
5922    public void wipeDataWithReason(int flags, String wipeReasonForUser) {
5923        if (!mHasFeature) {
5924            return;
5925        }
5926        Preconditions.checkStringNotEmpty(wipeReasonForUser, "wipeReasonForUser is null or empty");
5927        enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId());
5928
5929        final ActiveAdmin admin;
5930        synchronized (this) {
5931            admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA);
5932        }
5933        String internalReason = "DevicePolicyManager.wipeDataWithReason() from "
5934                + admin.info.getComponent().flattenToShortString();
5935        wipeDataNoLock(
5936                admin.info.getComponent(), flags, internalReason, wipeReasonForUser,
5937                admin.getUserHandle().getIdentifier());
5938    }
5939
5940    private void wipeDataNoLock(ComponentName admin, int flags, String internalReason,
5941                                String wipeReasonForUser, int userId) {
5942        wtfIfInLock();
5943
5944        long ident = mInjector.binderClearCallingIdentity();
5945        try {
5946            // First check whether the admin is allowed to wipe the device/user/profile.
5947            final String restriction;
5948            if (userId == UserHandle.USER_SYSTEM) {
5949                restriction = UserManager.DISALLOW_FACTORY_RESET;
5950            } else if (isManagedProfile(userId)) {
5951                restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
5952            } else {
5953                restriction = UserManager.DISALLOW_REMOVE_USER;
5954            }
5955            if (isAdminAffectedByRestriction(admin, restriction, userId)) {
5956                throw new SecurityException("Cannot wipe data. " + restriction
5957                        + " restriction is set for user " + userId);
5958            }
5959
5960            if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
5961                if (!isDeviceOwner(admin, userId)) {
5962                    throw new SecurityException(
5963                            "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
5964                }
5965                PersistentDataBlockManager manager = (PersistentDataBlockManager)
5966                        mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
5967                if (manager != null) {
5968                    manager.wipe();
5969                }
5970            }
5971
5972            // TODO If split user is enabled and the device owner is set in the primary user
5973            // (rather than system), we should probably trigger factory reset. Current code just
5974            // removes that user (but still clears FRP...)
5975            if (userId == UserHandle.USER_SYSTEM) {
5976                forceWipeDeviceNoLock(/*wipeExtRequested=*/ (
5977                        flags & WIPE_EXTERNAL_STORAGE) != 0,
5978                        internalReason,
5979                        /*wipeEuicc=*/ (flags & WIPE_EUICC) != 0);
5980            } else {
5981                forceWipeUser(userId, wipeReasonForUser);
5982            }
5983        } finally {
5984            mInjector.binderRestoreCallingIdentity(ident);
5985        }
5986    }
5987
5988    private void sendWipeProfileNotification(String wipeReasonForUser) {
5989        Notification notification =
5990                new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
5991                        .setSmallIcon(android.R.drawable.stat_sys_warning)
5992                        .setContentTitle(mContext.getString(R.string.work_profile_deleted))
5993                        .setContentText(wipeReasonForUser)
5994                        .setColor(mContext.getColor(R.color.system_notification_accent_color))
5995                        .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser))
5996                        .build();
5997        mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification);
5998    }
5999
6000    private void clearWipeProfileNotification() {
6001        mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED);
6002    }
6003
6004    @Override
6005    public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
6006        if (!mHasFeature) {
6007            return;
6008        }
6009        enforceFullCrossUsersPermission(userHandle);
6010        mContext.enforceCallingOrSelfPermission(
6011                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6012
6013        synchronized (this) {
6014            ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
6015            if (admin == null) {
6016                result.sendResult(null);
6017                return;
6018            }
6019            Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
6020            intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
6021            intent.setComponent(admin.info.getComponent());
6022            mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
6023                    null, new BroadcastReceiver() {
6024                @Override
6025                public void onReceive(Context context, Intent intent) {
6026                    result.sendResult(getResultExtras(false));
6027                }
6028            }, null, Activity.RESULT_OK, null, null);
6029        }
6030    }
6031
6032    /**
6033     * Notify DPMS regarding the metric of the current password. This happens when the user changes
6034     * the password, but also when the user just unlocks the keyguard. In comparison,
6035     * reportPasswordChanged() is only called when the user changes the password.
6036     */
6037    @Override
6038    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
6039        if (!mHasFeature) {
6040            return;
6041        }
6042        enforceFullCrossUsersPermission(userHandle);
6043        mContext.enforceCallingOrSelfPermission(
6044                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6045
6046        // If the managed profile doesn't have a separate password, set the metrics to default
6047        if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
6048            metrics = new PasswordMetrics();
6049        }
6050
6051        validateQualityConstant(metrics.quality);
6052        DevicePolicyData policy = getUserData(userHandle);
6053        synchronized (this) {
6054            policy.mActivePasswordMetrics = metrics;
6055            policy.mPasswordStateHasBeenSetSinceBoot = true;
6056        }
6057    }
6058
6059    @Override
6060    public void reportPasswordChanged(@UserIdInt int userId) {
6061        if (!mHasFeature) {
6062            return;
6063        }
6064        enforceFullCrossUsersPermission(userId);
6065
6066        // Managed Profile password can only be changed when it has a separate challenge.
6067        if (!isSeparateProfileChallengeEnabled(userId)) {
6068            enforceNotManagedProfile(userId, "set the active password");
6069        }
6070
6071        mContext.enforceCallingOrSelfPermission(
6072                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6073
6074        DevicePolicyData policy = getUserData(userId);
6075
6076        long ident = mInjector.binderClearCallingIdentity();
6077        try {
6078            synchronized (this) {
6079                policy.mFailedPasswordAttempts = 0;
6080                updatePasswordValidityCheckpointLocked(userId);
6081                saveSettingsLocked(userId);
6082                updatePasswordExpirationsLocked(userId);
6083                setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
6084
6085                // Send a broadcast to each profile using this password as its primary unlock.
6086                sendAdminCommandForLockscreenPoliciesLocked(
6087                        DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
6088                        DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
6089            }
6090            removeCaApprovalsIfNeeded(userId);
6091        } finally {
6092            mInjector.binderRestoreCallingIdentity(ident);
6093        }
6094    }
6095
6096    /**
6097     * Called any time the device password is updated. Resets all password expiration clocks.
6098     */
6099    private void updatePasswordExpirationsLocked(int userHandle) {
6100        ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
6101        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
6102                userHandle, /* parent */ false);
6103        final int N = admins.size();
6104        for (int i = 0; i < N; i++) {
6105            ActiveAdmin admin = admins.get(i);
6106            if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
6107                affectedUserIds.add(admin.getUserHandle().getIdentifier());
6108                long timeout = admin.passwordExpirationTimeout;
6109                long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
6110                admin.passwordExpirationDate = expiration;
6111            }
6112        }
6113        for (int affectedUserId : affectedUserIds) {
6114            saveSettingsLocked(affectedUserId);
6115        }
6116    }
6117
6118    @Override
6119    public void reportFailedPasswordAttempt(int userHandle) {
6120        enforceFullCrossUsersPermission(userHandle);
6121        if (!isSeparateProfileChallengeEnabled(userHandle)) {
6122            enforceNotManagedProfile(userHandle,
6123                    "report failed password attempt if separate profile challenge is not in place");
6124        }
6125        mContext.enforceCallingOrSelfPermission(
6126                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6127
6128        boolean wipeData = false;
6129        ActiveAdmin strictestAdmin = null;
6130        final long ident = mInjector.binderClearCallingIdentity();
6131        try {
6132            synchronized (this) {
6133                DevicePolicyData policy = getUserData(userHandle);
6134                policy.mFailedPasswordAttempts++;
6135                saveSettingsLocked(userHandle);
6136                if (mHasFeature) {
6137                    strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
6138                            userHandle, /* parent */ false);
6139                    int max = strictestAdmin != null
6140                            ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
6141                    if (max > 0 && policy.mFailedPasswordAttempts >= max) {
6142                        wipeData = true;
6143                    }
6144
6145                    sendAdminCommandForLockscreenPoliciesLocked(
6146                            DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
6147                            DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
6148                }
6149            }
6150        } finally {
6151            mInjector.binderRestoreCallingIdentity(ident);
6152        }
6153
6154        if (wipeData && strictestAdmin != null) {
6155            final int userId = strictestAdmin.getUserHandle().getIdentifier();
6156            Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
6157                    + strictestAdmin.info.getComponent().flattenToShortString()
6158                    + ". Calling wipeData for user " + userId);
6159
6160            // Attempt to wipe the device/user/profile associated with the admin, as if the
6161            // admin had called wipeData(). That way we can check whether the admin is actually
6162            // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
6163            // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
6164            // able to do so).
6165            // IMPORTANT: Call without holding the lock to prevent deadlock.
6166            try {
6167                String wipeReasonForUser = mContext.getString(
6168                        R.string.work_profile_deleted_reason_maximum_password_failure);
6169                wipeDataNoLock(strictestAdmin.info.getComponent(),
6170                        /*flags=*/ 0,
6171                        /*reason=*/ "reportFailedPasswordAttempt()",
6172                        wipeReasonForUser,
6173                        userId);
6174            } catch (SecurityException e) {
6175                Slog.w(LOG_TAG, "Failed to wipe user " + userId
6176                        + " after max failed password attempts reached.", e);
6177            }
6178        }
6179
6180        if (mInjector.securityLogIsLoggingEnabled()) {
6181            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
6182                    /*result*/ 0,
6183                    /*method strength*/ 1);
6184        }
6185    }
6186
6187    @Override
6188    public void reportSuccessfulPasswordAttempt(int userHandle) {
6189        enforceFullCrossUsersPermission(userHandle);
6190        mContext.enforceCallingOrSelfPermission(
6191                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6192
6193        synchronized (this) {
6194            DevicePolicyData policy = getUserData(userHandle);
6195            if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
6196                long ident = mInjector.binderClearCallingIdentity();
6197                try {
6198                    policy.mFailedPasswordAttempts = 0;
6199                    policy.mPasswordOwner = -1;
6200                    saveSettingsLocked(userHandle);
6201                    if (mHasFeature) {
6202                        sendAdminCommandForLockscreenPoliciesLocked(
6203                                DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
6204                                DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
6205                    }
6206                } finally {
6207                    mInjector.binderRestoreCallingIdentity(ident);
6208                }
6209            }
6210        }
6211
6212        if (mInjector.securityLogIsLoggingEnabled()) {
6213            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
6214                    /*method strength*/ 1);
6215        }
6216    }
6217
6218    @Override
6219    public void reportFailedFingerprintAttempt(int userHandle) {
6220        enforceFullCrossUsersPermission(userHandle);
6221        mContext.enforceCallingOrSelfPermission(
6222                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6223        if (mInjector.securityLogIsLoggingEnabled()) {
6224            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
6225                    /*method strength*/ 0);
6226        }
6227    }
6228
6229    @Override
6230    public void reportSuccessfulFingerprintAttempt(int userHandle) {
6231        enforceFullCrossUsersPermission(userHandle);
6232        mContext.enforceCallingOrSelfPermission(
6233                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6234        if (mInjector.securityLogIsLoggingEnabled()) {
6235            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
6236                    /*method strength*/ 0);
6237        }
6238    }
6239
6240    @Override
6241    public void reportKeyguardDismissed(int userHandle) {
6242        enforceFullCrossUsersPermission(userHandle);
6243        mContext.enforceCallingOrSelfPermission(
6244                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6245
6246        if (mInjector.securityLogIsLoggingEnabled()) {
6247            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
6248        }
6249    }
6250
6251    @Override
6252    public void reportKeyguardSecured(int userHandle) {
6253        enforceFullCrossUsersPermission(userHandle);
6254        mContext.enforceCallingOrSelfPermission(
6255                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6256
6257        if (mInjector.securityLogIsLoggingEnabled()) {
6258            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
6259        }
6260    }
6261
6262    @Override
6263    public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
6264            String exclusionList) {
6265        if (!mHasFeature) {
6266            return null;
6267        }
6268        synchronized(this) {
6269            Preconditions.checkNotNull(who, "ComponentName is null");
6270
6271            // Only check if system user has set global proxy. We don't allow other users to set it.
6272            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6273            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6274                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
6275
6276            // Scan through active admins and find if anyone has already
6277            // set the global proxy.
6278            Set<ComponentName> compSet = policy.mAdminMap.keySet();
6279            for (ComponentName component : compSet) {
6280                ActiveAdmin ap = policy.mAdminMap.get(component);
6281                if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
6282                    // Another admin already sets the global proxy
6283                    // Return it to the caller.
6284                    return component;
6285                }
6286            }
6287
6288            // If the user is not system, don't set the global proxy. Fail silently.
6289            if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
6290                Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
6291                        + UserHandle.getCallingUserId() + " is not permitted.");
6292                return null;
6293            }
6294            if (proxySpec == null) {
6295                admin.specifiesGlobalProxy = false;
6296                admin.globalProxySpec = null;
6297                admin.globalProxyExclusionList = null;
6298            } else {
6299
6300                admin.specifiesGlobalProxy = true;
6301                admin.globalProxySpec = proxySpec;
6302                admin.globalProxyExclusionList = exclusionList;
6303            }
6304
6305            // Reset the global proxy accordingly
6306            // Do this using system permissions, as apps cannot write to secure settings
6307            long origId = mInjector.binderClearCallingIdentity();
6308            try {
6309                resetGlobalProxyLocked(policy);
6310            } finally {
6311                mInjector.binderRestoreCallingIdentity(origId);
6312            }
6313            return null;
6314        }
6315    }
6316
6317    @Override
6318    public ComponentName getGlobalProxyAdmin(int userHandle) {
6319        if (!mHasFeature) {
6320            return null;
6321        }
6322        enforceFullCrossUsersPermission(userHandle);
6323        synchronized(this) {
6324            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6325            // Scan through active admins and find if anyone has already
6326            // set the global proxy.
6327            final int N = policy.mAdminList.size();
6328            for (int i = 0; i < N; i++) {
6329                ActiveAdmin ap = policy.mAdminList.get(i);
6330                if (ap.specifiesGlobalProxy) {
6331                    // Device admin sets the global proxy
6332                    // Return it to the caller.
6333                    return ap.info.getComponent();
6334                }
6335            }
6336        }
6337        // No device admin sets the global proxy.
6338        return null;
6339    }
6340
6341    @Override
6342    public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
6343        synchronized (this) {
6344            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6345        }
6346        long token = mInjector.binderClearCallingIdentity();
6347        try {
6348            ConnectivityManager connectivityManager = (ConnectivityManager)
6349                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
6350            connectivityManager.setGlobalProxy(proxyInfo);
6351        } finally {
6352            mInjector.binderRestoreCallingIdentity(token);
6353        }
6354    }
6355
6356    private void resetGlobalProxyLocked(DevicePolicyData policy) {
6357        final int N = policy.mAdminList.size();
6358        for (int i = 0; i < N; i++) {
6359            ActiveAdmin ap = policy.mAdminList.get(i);
6360            if (ap.specifiesGlobalProxy) {
6361                saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
6362                return;
6363            }
6364        }
6365        // No device admins defining global proxies - reset global proxy settings to none
6366        saveGlobalProxyLocked(null, null);
6367    }
6368
6369    private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
6370        if (exclusionList == null) {
6371            exclusionList = "";
6372        }
6373        if (proxySpec == null) {
6374            proxySpec = "";
6375        }
6376        // Remove white spaces
6377        proxySpec = proxySpec.trim();
6378        String data[] = proxySpec.split(":");
6379        int proxyPort = 8080;
6380        if (data.length > 1) {
6381            try {
6382                proxyPort = Integer.parseInt(data[1]);
6383            } catch (NumberFormatException e) {}
6384        }
6385        exclusionList = exclusionList.trim();
6386
6387        ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
6388        if (!proxyProperties.isValid()) {
6389            Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
6390            return;
6391        }
6392        mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
6393        mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
6394        mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
6395                exclusionList);
6396    }
6397
6398    /**
6399     * Set the storage encryption request for a single admin.  Returns the new total request
6400     * status (for all admins).
6401     */
6402    @Override
6403    public int setStorageEncryption(ComponentName who, boolean encrypt) {
6404        if (!mHasFeature) {
6405            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6406        }
6407        Preconditions.checkNotNull(who, "ComponentName is null");
6408        final int userHandle = UserHandle.getCallingUserId();
6409        synchronized (this) {
6410            // Check for permissions
6411            // Only system user can set storage encryption
6412            if (userHandle != UserHandle.USER_SYSTEM) {
6413                Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
6414                        + UserHandle.getCallingUserId() + " is not permitted.");
6415                return 0;
6416            }
6417
6418            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6419                    DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
6420
6421            // Quick exit:  If the filesystem does not support encryption, we can exit early.
6422            if (!isEncryptionSupported()) {
6423                return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6424            }
6425
6426            // (1) Record the value for the admin so it's sticky
6427            if (ap.encryptionRequested != encrypt) {
6428                ap.encryptionRequested = encrypt;
6429                saveSettingsLocked(userHandle);
6430            }
6431
6432            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6433            // (2) Compute "max" for all admins
6434            boolean newRequested = false;
6435            final int N = policy.mAdminList.size();
6436            for (int i = 0; i < N; i++) {
6437                newRequested |= policy.mAdminList.get(i).encryptionRequested;
6438            }
6439
6440            // Notify OS of new request
6441            setEncryptionRequested(newRequested);
6442
6443            // Return the new global request status
6444            return newRequested
6445                    ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
6446                    : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
6447        }
6448    }
6449
6450    /**
6451     * Get the current storage encryption request status for a given admin, or aggregate of all
6452     * active admins.
6453     */
6454    @Override
6455    public boolean getStorageEncryption(ComponentName who, int userHandle) {
6456        if (!mHasFeature) {
6457            return false;
6458        }
6459        enforceFullCrossUsersPermission(userHandle);
6460        synchronized (this) {
6461            // Check for permissions if a particular caller is specified
6462            if (who != null) {
6463                // When checking for a single caller, status is based on caller's request
6464                ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
6465                return ap != null ? ap.encryptionRequested : false;
6466            }
6467
6468            // If no particular caller is specified, return the aggregate set of requests.
6469            // This is short circuited by returning true on the first hit.
6470            DevicePolicyData policy = getUserData(userHandle);
6471            final int N = policy.mAdminList.size();
6472            for (int i = 0; i < N; i++) {
6473                if (policy.mAdminList.get(i).encryptionRequested) {
6474                    return true;
6475                }
6476            }
6477            return false;
6478        }
6479    }
6480
6481    /**
6482     * Get the current encryption status of the device.
6483     */
6484    @Override
6485    public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
6486        if (!mHasFeature) {
6487            // Ok to return current status.
6488        }
6489        enforceFullCrossUsersPermission(userHandle);
6490
6491        // It's not critical here, but let's make sure the package name is correct, in case
6492        // we start using it for different purposes.
6493        ensureCallerPackage(callerPackage);
6494
6495        final ApplicationInfo ai;
6496        try {
6497            ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
6498        } catch (RemoteException e) {
6499            throw new SecurityException(e);
6500        }
6501
6502        boolean legacyApp = false;
6503        if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
6504            legacyApp = true;
6505        }
6506
6507        final int rawStatus = getEncryptionStatus();
6508        if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
6509            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
6510        }
6511        return rawStatus;
6512    }
6513
6514    /**
6515     * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
6516     */
6517    private boolean isEncryptionSupported() {
6518        // Note, this can be implemented as
6519        //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6520        // But is provided as a separate internal method if there's a faster way to do a
6521        // simple check for supported-or-not.
6522        return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6523    }
6524
6525    /**
6526     * Hook to low-levels:  Reporting the current status of encryption.
6527     * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
6528     * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
6529     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
6530     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
6531     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
6532     */
6533    private int getEncryptionStatus() {
6534        if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
6535            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
6536        } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
6537            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
6538        } else if (mInjector.storageManagerIsEncrypted()) {
6539            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
6540        } else if (mInjector.storageManagerIsEncryptable()) {
6541            return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
6542        } else {
6543            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6544        }
6545    }
6546
6547    /**
6548     * Hook to low-levels:  If needed, record the new admin setting for encryption.
6549     */
6550    private void setEncryptionRequested(boolean encrypt) {
6551    }
6552
6553    /**
6554     * Set whether the screen capture is disabled for the user managed by the specified admin.
6555     */
6556    @Override
6557    public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
6558        if (!mHasFeature) {
6559            return;
6560        }
6561        Preconditions.checkNotNull(who, "ComponentName is null");
6562        final int userHandle = UserHandle.getCallingUserId();
6563        synchronized (this) {
6564            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6565                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6566            if (ap.disableScreenCapture != disabled) {
6567                ap.disableScreenCapture = disabled;
6568                saveSettingsLocked(userHandle);
6569                updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
6570            }
6571        }
6572    }
6573
6574    /**
6575     * Returns whether or not screen capture is disabled for a given admin, or disabled for any
6576     * active admin (if given admin is null).
6577     */
6578    @Override
6579    public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
6580        if (!mHasFeature) {
6581            return false;
6582        }
6583        synchronized (this) {
6584            if (who != null) {
6585                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6586                return (admin != null) ? admin.disableScreenCapture : false;
6587            }
6588
6589            DevicePolicyData policy = getUserData(userHandle);
6590            final int N = policy.mAdminList.size();
6591            for (int i = 0; i < N; i++) {
6592                ActiveAdmin admin = policy.mAdminList.get(i);
6593                if (admin.disableScreenCapture) {
6594                    return true;
6595                }
6596            }
6597            return false;
6598        }
6599    }
6600
6601    private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
6602            final boolean disabled) {
6603        mHandler.post(new Runnable() {
6604            @Override
6605            public void run() {
6606                try {
6607                    mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
6608                } catch (RemoteException e) {
6609                    Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
6610                }
6611            }
6612        });
6613    }
6614
6615    /**
6616     * Set whether auto time is required by the specified admin (must be device or profile owner).
6617     */
6618    @Override
6619    public void setAutoTimeRequired(ComponentName who, boolean required) {
6620        if (!mHasFeature) {
6621            return;
6622        }
6623        Preconditions.checkNotNull(who, "ComponentName is null");
6624        final int userHandle = UserHandle.getCallingUserId();
6625        synchronized (this) {
6626            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6627                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6628            if (admin.requireAutoTime != required) {
6629                admin.requireAutoTime = required;
6630                saveSettingsLocked(userHandle);
6631            }
6632        }
6633
6634        // Turn AUTO_TIME on in settings if it is required
6635        if (required) {
6636            long ident = mInjector.binderClearCallingIdentity();
6637            try {
6638                mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
6639            } finally {
6640                mInjector.binderRestoreCallingIdentity(ident);
6641            }
6642        }
6643    }
6644
6645    /**
6646     * Returns whether or not auto time is required by the device owner or any profile owner.
6647     */
6648    @Override
6649    public boolean getAutoTimeRequired() {
6650        if (!mHasFeature) {
6651            return false;
6652        }
6653        synchronized (this) {
6654            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6655            if (deviceOwner != null && deviceOwner.requireAutoTime) {
6656                // If the device owner enforces auto time, we don't need to check the PO's
6657                return true;
6658            }
6659
6660            // Now check to see if any profile owner on any user enforces auto time
6661            for (Integer userId : mOwners.getProfileOwnerKeys()) {
6662                ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
6663                if (profileOwner != null && profileOwner.requireAutoTime) {
6664                    return true;
6665                }
6666            }
6667
6668            return false;
6669        }
6670    }
6671
6672    @Override
6673    public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
6674        if (!mHasFeature) {
6675            return;
6676        }
6677        Preconditions.checkNotNull(who, "ComponentName is null");
6678        // Allow setting this policy to true only if there is a split system user.
6679        if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
6680            throw new UnsupportedOperationException(
6681                    "Cannot force ephemeral users on systems without split system user.");
6682        }
6683        boolean removeAllUsers = false;
6684        synchronized (this) {
6685            final ActiveAdmin deviceOwner =
6686                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6687            if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
6688                deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
6689                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
6690                mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
6691                removeAllUsers = forceEphemeralUsers;
6692            }
6693        }
6694        if (removeAllUsers) {
6695            long identitity = mInjector.binderClearCallingIdentity();
6696            try {
6697                mUserManagerInternal.removeAllUsers();
6698            } finally {
6699                mInjector.binderRestoreCallingIdentity(identitity);
6700            }
6701        }
6702    }
6703
6704    @Override
6705    public boolean getForceEphemeralUsers(ComponentName who) {
6706        if (!mHasFeature) {
6707            return false;
6708        }
6709        Preconditions.checkNotNull(who, "ComponentName is null");
6710        synchronized (this) {
6711            final ActiveAdmin deviceOwner =
6712                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6713            return deviceOwner.forceEphemeralUsers;
6714        }
6715    }
6716
6717    private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) throws SecurityException {
6718        synchronized (this) {
6719            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6720            if (!areAllUsersAffiliatedWithDeviceLocked()) {
6721                throw new SecurityException("Not all users are affiliated.");
6722            }
6723        }
6724    }
6725
6726    @Override
6727    public boolean requestBugreport(ComponentName who) {
6728        if (!mHasFeature) {
6729            return false;
6730        }
6731        Preconditions.checkNotNull(who, "ComponentName is null");
6732
6733        // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
6734        // which could still contain data related to that user. Should we disallow that, e.g. until
6735        // next boot? Might not be needed given that this still requires user consent.
6736        ensureDeviceOwnerAndAllUsersAffiliated(who);
6737
6738        if (mRemoteBugreportServiceIsActive.get()
6739                || (getDeviceOwnerRemoteBugreportUri() != null)) {
6740            Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
6741            return false;
6742        }
6743
6744        final long currentTime = System.currentTimeMillis();
6745        synchronized (this) {
6746            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
6747            if (currentTime > policyData.mLastBugReportRequestTime) {
6748                policyData.mLastBugReportRequestTime = currentTime;
6749                saveSettingsLocked(UserHandle.USER_SYSTEM);
6750            }
6751        }
6752
6753        final long callingIdentity = mInjector.binderClearCallingIdentity();
6754        try {
6755            mInjector.getIActivityManager().requestBugReport(
6756                    ActivityManager.BUGREPORT_OPTION_REMOTE);
6757
6758            mRemoteBugreportServiceIsActive.set(true);
6759            mRemoteBugreportSharingAccepted.set(false);
6760            registerRemoteBugreportReceivers();
6761            mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
6762                    RemoteBugreportUtils.NOTIFICATION_ID,
6763                    RemoteBugreportUtils.buildNotification(mContext,
6764                            DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
6765            mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
6766                    RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
6767            return true;
6768        } catch (RemoteException re) {
6769            // should never happen
6770            Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
6771            return false;
6772        } finally {
6773            mInjector.binderRestoreCallingIdentity(callingIdentity);
6774        }
6775    }
6776
6777    void sendDeviceOwnerCommand(String action, Bundle extras) {
6778        int deviceOwnerUserId;
6779        ComponentName deviceOwnerComponent;
6780        synchronized (this) {
6781            deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6782            deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6783        }
6784        sendActiveAdminCommand(action, extras, deviceOwnerUserId,
6785                deviceOwnerComponent);
6786    }
6787
6788    private void sendProfileOwnerCommand(String action, Bundle extras, int userHandle) {
6789        sendActiveAdminCommand(action, extras, userHandle,
6790                mOwners.getProfileOwnerComponent(userHandle));
6791    }
6792
6793    private void sendActiveAdminCommand(String action, Bundle extras,
6794            int userHandle, ComponentName receiverComponent) {
6795        final Intent intent = new Intent(action);
6796        intent.setComponent(receiverComponent);
6797        if (extras != null) {
6798            intent.putExtras(extras);
6799        }
6800        mContext.sendBroadcastAsUser(intent, UserHandle.of(userHandle));
6801    }
6802
6803    private void sendOwnerChangedBroadcast(String broadcast, int userId) {
6804        final Intent intent = new Intent(broadcast)
6805                .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
6806        mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
6807    }
6808
6809    private synchronized String getDeviceOwnerRemoteBugreportUri() {
6810        return mOwners.getDeviceOwnerRemoteBugreportUri();
6811    }
6812
6813    private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
6814            String bugreportHash) {
6815        mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
6816    }
6817
6818    private void registerRemoteBugreportReceivers() {
6819        try {
6820            IntentFilter filterFinished = new IntentFilter(
6821                    DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
6822                    RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6823            mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
6824        } catch (IntentFilter.MalformedMimeTypeException e) {
6825            // should never happen, as setting a constant
6826            Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
6827        }
6828        IntentFilter filterConsent = new IntentFilter();
6829        filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
6830        filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
6831        mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
6832    }
6833
6834    private void onBugreportFinished(Intent intent) {
6835        mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6836        mRemoteBugreportServiceIsActive.set(false);
6837        Uri bugreportUri = intent.getData();
6838        String bugreportUriString = null;
6839        if (bugreportUri != null) {
6840            bugreportUriString = bugreportUri.toString();
6841        }
6842        String bugreportHash = intent.getStringExtra(
6843                DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
6844        if (mRemoteBugreportSharingAccepted.get()) {
6845            shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6846            mInjector.getNotificationManager().cancel(LOG_TAG,
6847                    RemoteBugreportUtils.NOTIFICATION_ID);
6848        } else {
6849            setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
6850            mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6851                    RemoteBugreportUtils.buildNotification(mContext,
6852                            DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
6853                            UserHandle.ALL);
6854        }
6855        mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6856    }
6857
6858    private void onBugreportFailed() {
6859        mRemoteBugreportServiceIsActive.set(false);
6860        mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6861                RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6862        mRemoteBugreportSharingAccepted.set(false);
6863        setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6864        mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
6865        Bundle extras = new Bundle();
6866        extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6867                DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
6868        sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6869        mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
6870        mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6871    }
6872
6873    private void onBugreportSharingAccepted() {
6874        mRemoteBugreportSharingAccepted.set(true);
6875        String bugreportUriString = null;
6876        String bugreportHash = null;
6877        synchronized (this) {
6878            bugreportUriString = getDeviceOwnerRemoteBugreportUri();
6879            bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
6880        }
6881        if (bugreportUriString != null) {
6882            shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6883        } else if (mRemoteBugreportServiceIsActive.get()) {
6884            mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6885                    RemoteBugreportUtils.buildNotification(mContext,
6886                            DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
6887                            UserHandle.ALL);
6888        }
6889    }
6890
6891    private void onBugreportSharingDeclined() {
6892        if (mRemoteBugreportServiceIsActive.get()) {
6893            mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6894                    RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6895            mRemoteBugreportServiceIsActive.set(false);
6896            mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6897            mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6898        }
6899        mRemoteBugreportSharingAccepted.set(false);
6900        setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6901        sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
6902    }
6903
6904    private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
6905            String bugreportHash) {
6906        ParcelFileDescriptor pfd = null;
6907        try {
6908            if (bugreportUriString == null) {
6909                throw new FileNotFoundException();
6910            }
6911            Uri bugreportUri = Uri.parse(bugreportUriString);
6912            pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
6913
6914            synchronized (this) {
6915                Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
6916                intent.setComponent(mOwners.getDeviceOwnerComponent());
6917                intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6918                intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
6919                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
6920
6921                LocalServices.getService(ActivityManagerInternal.class)
6922                        .grantUriPermissionFromIntent(Process.SHELL_UID,
6923                                mOwners.getDeviceOwnerComponent().getPackageName(),
6924                                intent, mOwners.getDeviceOwnerUserId());
6925                mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
6926            }
6927        } catch (FileNotFoundException e) {
6928            Bundle extras = new Bundle();
6929            extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6930                    DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
6931            sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6932        } finally {
6933            try {
6934                if (pfd != null) {
6935                    pfd.close();
6936                }
6937            } catch (IOException ex) {
6938                // Ignore
6939            }
6940            mRemoteBugreportSharingAccepted.set(false);
6941            setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6942        }
6943    }
6944
6945    /**
6946     * Disables all device cameras according to the specified admin.
6947     */
6948    @Override
6949    public void setCameraDisabled(ComponentName who, boolean disabled) {
6950        if (!mHasFeature) {
6951            return;
6952        }
6953        Preconditions.checkNotNull(who, "ComponentName is null");
6954        final int userHandle = mInjector.userHandleGetCallingUserId();
6955        synchronized (this) {
6956            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6957                    DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
6958            if (ap.disableCamera != disabled) {
6959                ap.disableCamera = disabled;
6960                saveSettingsLocked(userHandle);
6961            }
6962        }
6963        // Tell the user manager that the restrictions have changed.
6964        pushUserRestrictions(userHandle);
6965    }
6966
6967    /**
6968     * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
6969     * active admins.
6970     */
6971    @Override
6972    public boolean getCameraDisabled(ComponentName who, int userHandle) {
6973        return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
6974    }
6975
6976    private boolean getCameraDisabled(ComponentName who, int userHandle,
6977            boolean mergeDeviceOwnerRestriction) {
6978        if (!mHasFeature) {
6979            return false;
6980        }
6981        synchronized (this) {
6982            if (who != null) {
6983                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6984                return (admin != null) ? admin.disableCamera : false;
6985            }
6986            // First, see if DO has set it.  If so, it's device-wide.
6987            if (mergeDeviceOwnerRestriction) {
6988                final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6989                if (deviceOwner != null && deviceOwner.disableCamera) {
6990                    return true;
6991                }
6992            }
6993
6994            // Then check each device admin on the user.
6995            DevicePolicyData policy = getUserData(userHandle);
6996            // Determine whether or not the device camera is disabled for any active admins.
6997            final int N = policy.mAdminList.size();
6998            for (int i = 0; i < N; i++) {
6999                ActiveAdmin admin = policy.mAdminList.get(i);
7000                if (admin.disableCamera) {
7001                    return true;
7002                }
7003            }
7004            return false;
7005        }
7006    }
7007
7008    @Override
7009    public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
7010        if (!mHasFeature) {
7011            return;
7012        }
7013        Preconditions.checkNotNull(who, "ComponentName is null");
7014        final int userHandle = mInjector.userHandleGetCallingUserId();
7015        if (isManagedProfile(userHandle)) {
7016            if (parent) {
7017                which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
7018            } else {
7019                which = which & PROFILE_KEYGUARD_FEATURES;
7020            }
7021        }
7022        synchronized (this) {
7023            ActiveAdmin ap = getActiveAdminForCallerLocked(
7024                    who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
7025            if (ap.disabledKeyguardFeatures != which) {
7026                ap.disabledKeyguardFeatures = which;
7027                saveSettingsLocked(userHandle);
7028            }
7029        }
7030    }
7031
7032    /**
7033     * Gets the disabled state for features in keyguard for the given admin,
7034     * or the aggregate of all active admins if who is null.
7035     */
7036    @Override
7037    public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
7038        if (!mHasFeature) {
7039            return 0;
7040        }
7041        enforceFullCrossUsersPermission(userHandle);
7042        final long ident = mInjector.binderClearCallingIdentity();
7043        try {
7044            synchronized (this) {
7045                if (who != null) {
7046                    ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
7047                    return (admin != null) ? admin.disabledKeyguardFeatures : 0;
7048                }
7049
7050                final List<ActiveAdmin> admins;
7051                if (!parent && isManagedProfile(userHandle)) {
7052                    // If we are being asked about a managed profile, just return keyguard features
7053                    // disabled by admins in the profile.
7054                    admins = getUserDataUnchecked(userHandle).mAdminList;
7055                } else {
7056                    // Otherwise return those set by admins in the user and its profiles.
7057                    admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
7058                }
7059
7060                int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
7061                final int N = admins.size();
7062                for (int i = 0; i < N; i++) {
7063                    ActiveAdmin admin = admins.get(i);
7064                    int userId = admin.getUserHandle().getIdentifier();
7065                    boolean isRequestedUser = !parent && (userId == userHandle);
7066                    if (isRequestedUser || !isManagedProfile(userId)) {
7067                        // If we are being asked explicitly about this user
7068                        // return all disabled features even if its a managed profile.
7069                        which |= admin.disabledKeyguardFeatures;
7070                    } else {
7071                        // Otherwise a managed profile is only allowed to disable
7072                        // some features on the parent user.
7073                        which |= (admin.disabledKeyguardFeatures
7074                                & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
7075                    }
7076                }
7077                return which;
7078            }
7079        } finally {
7080            mInjector.binderRestoreCallingIdentity(ident);
7081        }
7082    }
7083
7084    @Override
7085    public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
7086            List<String> packageList) {
7087        if (!mHasFeature) {
7088            return;
7089        }
7090        Preconditions.checkNotNull(packageList, "packageList is null");
7091        final int userHandle = UserHandle.getCallingUserId();
7092        synchronized (this) {
7093            // Ensure the caller is a DO or a keep uninstalled packages delegate.
7094            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7095                    DELEGATION_KEEP_UNINSTALLED_PACKAGES);
7096            // Get the device owner
7097            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7098            // Set list of packages to be kept even if uninstalled.
7099            deviceOwner.keepUninstalledPackages = packageList;
7100            // Save settings.
7101            saveSettingsLocked(userHandle);
7102            // Notify package manager.
7103            mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
7104        }
7105    }
7106
7107    @Override
7108    public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
7109        if (!mHasFeature) {
7110            return null;
7111        }
7112        // TODO In split system user mode, allow apps on user 0 to query the list
7113        synchronized (this) {
7114            // Ensure the caller is a DO or a keep uninstalled packages delegate.
7115            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7116                    DELEGATION_KEEP_UNINSTALLED_PACKAGES);
7117            return getKeepUninstalledPackagesLocked();
7118        }
7119    }
7120
7121    private List<String> getKeepUninstalledPackagesLocked() {
7122        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7123        return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
7124    }
7125
7126    @Override
7127    public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
7128        if (!mHasFeature) {
7129            return false;
7130        }
7131        if (admin == null
7132                || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
7133            throw new IllegalArgumentException("Invalid component " + admin
7134                    + " for device owner");
7135        }
7136        final boolean hasIncompatibleAccountsOrNonAdb =
7137                hasIncompatibleAccountsOrNonAdbNoLock(userId, admin);
7138        synchronized (this) {
7139            enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb);
7140            final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
7141            if (activeAdmin == null
7142                    || getUserData(userId).mRemovingAdmins.contains(admin)) {
7143                throw new IllegalArgumentException("Not active admin: " + admin);
7144            }
7145
7146            // Shutting down backup manager service permanently.
7147            long ident = mInjector.binderClearCallingIdentity();
7148            try {
7149                if (mInjector.getIBackupManager() != null) {
7150                    mInjector.getIBackupManager()
7151                            .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
7152                }
7153            } catch (RemoteException e) {
7154                throw new IllegalStateException("Failed deactivating backup service.", e);
7155            } finally {
7156                mInjector.binderRestoreCallingIdentity(ident);
7157            }
7158
7159            if (isAdb()) {
7160                // Log device owner provisioning was started using adb.
7161                MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
7162            }
7163
7164            mOwners.setDeviceOwner(admin, ownerName, userId);
7165            mOwners.writeDeviceOwner();
7166            updateDeviceOwnerLocked();
7167            setDeviceOwnerSystemPropertyLocked();
7168
7169            final Set<String> restrictions =
7170                    UserRestrictionsUtils.getDefaultEnabledForDeviceOwner();
7171            if (!restrictions.isEmpty()) {
7172                for (String restriction : restrictions) {
7173                    activeAdmin.ensureUserRestrictions().putBoolean(restriction, true);
7174                }
7175                activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions);
7176                Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions);
7177
7178                saveUserRestrictionsLocked(userId);
7179            }
7180
7181            ident = mInjector.binderClearCallingIdentity();
7182            try {
7183                // TODO Send to system too?
7184                sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId);
7185            } finally {
7186                mInjector.binderRestoreCallingIdentity(ident);
7187            }
7188            mDeviceAdminServiceController.startServiceForOwner(
7189                    admin.getPackageName(), userId, "set-device-owner");
7190
7191            Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
7192            return true;
7193        }
7194    }
7195
7196    @Override
7197    public boolean hasDeviceOwner() {
7198        enforceDeviceOwnerOrManageUsers();
7199        return mOwners.hasDeviceOwner();
7200    }
7201
7202    boolean isDeviceOwner(ActiveAdmin admin) {
7203        return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
7204    }
7205
7206    public boolean isDeviceOwner(ComponentName who, int userId) {
7207        synchronized (this) {
7208            return mOwners.hasDeviceOwner()
7209                    && mOwners.getDeviceOwnerUserId() == userId
7210                    && mOwners.getDeviceOwnerComponent().equals(who);
7211        }
7212    }
7213
7214    private boolean isDeviceOwnerPackage(String packageName, int userId) {
7215        synchronized (this) {
7216            return mOwners.hasDeviceOwner()
7217                    && mOwners.getDeviceOwnerUserId() == userId
7218                    && mOwners.getDeviceOwnerPackageName().equals(packageName);
7219        }
7220    }
7221
7222    private boolean isProfileOwnerPackage(String packageName, int userId) {
7223        synchronized (this) {
7224            return mOwners.hasProfileOwner(userId)
7225                    && mOwners.getProfileOwnerPackage(userId).equals(packageName);
7226        }
7227    }
7228
7229    public boolean isProfileOwner(ComponentName who, int userId) {
7230        final ComponentName profileOwner = getProfileOwner(userId);
7231        return who != null && who.equals(profileOwner);
7232    }
7233
7234    @Override
7235    public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
7236        if (!mHasFeature) {
7237            return null;
7238        }
7239        if (!callingUserOnly) {
7240            enforceManageUsers();
7241        }
7242        synchronized (this) {
7243            if (!mOwners.hasDeviceOwner()) {
7244                return null;
7245            }
7246            if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
7247                    mOwners.getDeviceOwnerUserId()) {
7248                return null;
7249            }
7250            return mOwners.getDeviceOwnerComponent();
7251        }
7252    }
7253
7254    @Override
7255    public int getDeviceOwnerUserId() {
7256        if (!mHasFeature) {
7257            return UserHandle.USER_NULL;
7258        }
7259        enforceManageUsers();
7260        synchronized (this) {
7261            return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
7262        }
7263    }
7264
7265    /**
7266     * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
7267     * MANAGE_USERS.
7268     */
7269    @Override
7270    public String getDeviceOwnerName() {
7271        if (!mHasFeature) {
7272            return null;
7273        }
7274        enforceManageUsers();
7275        synchronized (this) {
7276            if (!mOwners.hasDeviceOwner()) {
7277                return null;
7278            }
7279            // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
7280            // Should setDeviceOwner/ProfileOwner still take a name?
7281            String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
7282            return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
7283        }
7284    }
7285
7286    /** Returns the active device owner or {@code null} if there is no device owner. */
7287    @VisibleForTesting
7288    ActiveAdmin getDeviceOwnerAdminLocked() {
7289        ComponentName component = mOwners.getDeviceOwnerComponent();
7290        if (component == null) {
7291            return null;
7292        }
7293
7294        DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
7295        final int n = policy.mAdminList.size();
7296        for (int i = 0; i < n; i++) {
7297            ActiveAdmin admin = policy.mAdminList.get(i);
7298            if (component.equals(admin.info.getComponent())) {
7299                return admin;
7300            }
7301        }
7302        Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
7303        return null;
7304    }
7305
7306    @Override
7307    public void clearDeviceOwner(String packageName) {
7308        Preconditions.checkNotNull(packageName, "packageName is null");
7309        final int callingUid = mInjector.binderGetCallingUid();
7310        try {
7311            int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName,
7312                    UserHandle.getUserId(callingUid));
7313            if (uid != callingUid) {
7314                throw new SecurityException("Invalid packageName");
7315            }
7316        } catch (NameNotFoundException e) {
7317            throw new SecurityException(e);
7318        }
7319        synchronized (this) {
7320            final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
7321            final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
7322            if (!mOwners.hasDeviceOwner()
7323                    || !deviceOwnerComponent.getPackageName().equals(packageName)
7324                    || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
7325                throw new SecurityException(
7326                        "clearDeviceOwner can only be called by the device owner");
7327            }
7328            enforceUserUnlocked(deviceOwnerUserId);
7329
7330            final ActiveAdmin admin = getDeviceOwnerAdminLocked();
7331            long ident = mInjector.binderClearCallingIdentity();
7332            try {
7333                clearDeviceOwnerLocked(admin, deviceOwnerUserId);
7334                removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
7335                sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED,
7336                        deviceOwnerUserId);
7337            } finally {
7338                mInjector.binderRestoreCallingIdentity(ident);
7339            }
7340            Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
7341        }
7342    }
7343
7344    private void clearOverrideApnUnchecked() {
7345        // Disable Override APNs and remove them from database.
7346        setOverrideApnsEnabledUnchecked(false);
7347        final List<ApnSetting> apns = getOverrideApnsUnchecked();
7348        for (int i = 0; i < apns.size(); i ++) {
7349            removeOverrideApnUnchecked(apns.get(i).getId());
7350        }
7351    }
7352
7353    private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
7354        mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner");
7355
7356        if (admin != null) {
7357            admin.disableCamera = false;
7358            admin.userRestrictions = null;
7359            admin.defaultEnabledRestrictionsAlreadySet.clear();
7360            admin.forceEphemeralUsers = false;
7361            admin.isNetworkLoggingEnabled = false;
7362            mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
7363        }
7364        final DevicePolicyData policyData = getUserData(userId);
7365        policyData.mCurrentInputMethodSet = false;
7366        saveSettingsLocked(userId);
7367        final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM);
7368        systemPolicyData.mLastSecurityLogRetrievalTime = -1;
7369        systemPolicyData.mLastBugReportRequestTime = -1;
7370        systemPolicyData.mLastNetworkLogsRetrievalTime = -1;
7371        saveSettingsLocked(UserHandle.USER_SYSTEM);
7372        clearUserPoliciesLocked(userId);
7373        clearOverrideApnUnchecked();
7374
7375        mOwners.clearDeviceOwner();
7376        mOwners.writeDeviceOwner();
7377        updateDeviceOwnerLocked();
7378
7379        clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId));
7380        mInjector.securityLogSetLoggingEnabledProperty(false);
7381        mSecurityLogMonitor.stop();
7382        setNetworkLoggingActiveInternal(false);
7383        deleteTransferOwnershipBundleLocked(userId);
7384
7385        try {
7386            if (mInjector.getIBackupManager() != null) {
7387                // Reactivate backup service.
7388                mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
7389            }
7390        } catch (RemoteException e) {
7391            throw new IllegalStateException("Failed reactivating backup service.", e);
7392        }
7393    }
7394
7395    @Override
7396    public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
7397        if (!mHasFeature) {
7398            return false;
7399        }
7400        if (who == null
7401                || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
7402            throw new IllegalArgumentException("Component " + who
7403                    + " not installed for userId:" + userHandle);
7404        }
7405        final boolean hasIncompatibleAccountsOrNonAdb =
7406                hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who);
7407        synchronized (this) {
7408            enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb);
7409
7410            final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7411            if (admin == null || getUserData(userHandle).mRemovingAdmins.contains(who)) {
7412                throw new IllegalArgumentException("Not active admin: " + who);
7413            }
7414
7415            if (isAdb()) {
7416                // Log profile owner provisioning was started using adb.
7417                MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
7418            }
7419
7420            mOwners.setProfileOwner(who, ownerName, userHandle);
7421            mOwners.writeProfileOwner(userHandle);
7422            Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
7423
7424            final long id = mInjector.binderClearCallingIdentity();
7425            try {
7426                if (mUserManager.isManagedProfile(userHandle)) {
7427                    maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin,
7428                            UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
7429                    ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin,
7430                            true /* newOwner */);
7431                }
7432                sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
7433                        userHandle);
7434            } finally {
7435                mInjector.binderRestoreCallingIdentity(id);
7436            }
7437            mDeviceAdminServiceController.startServiceForOwner(
7438                    who.getPackageName(), userHandle, "set-profile-owner");
7439            return true;
7440        }
7441    }
7442
7443    @Override
7444    public void clearProfileOwner(ComponentName who) {
7445        if (!mHasFeature) {
7446            return;
7447        }
7448        Preconditions.checkNotNull(who, "ComponentName is null");
7449
7450        final int userId = mInjector.userHandleGetCallingUserId();
7451        enforceNotManagedProfile(userId, "clear profile owner");
7452        enforceUserUnlocked(userId);
7453        synchronized (this) {
7454            // Check if this is the profile owner who is calling
7455            final ActiveAdmin admin =
7456                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7457
7458            final long ident = mInjector.binderClearCallingIdentity();
7459            try {
7460                clearProfileOwnerLocked(admin, userId);
7461                removeActiveAdminLocked(who, userId);
7462                sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
7463                        userId);
7464            } finally {
7465                mInjector.binderRestoreCallingIdentity(ident);
7466            }
7467            Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
7468        }
7469    }
7470
7471    public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
7472        mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner");
7473
7474        if (admin != null) {
7475            admin.disableCamera = false;
7476            admin.userRestrictions = null;
7477            admin.defaultEnabledRestrictionsAlreadySet.clear();
7478        }
7479        final DevicePolicyData policyData = getUserData(userId);
7480        policyData.mCurrentInputMethodSet = false;
7481        policyData.mOwnerInstalledCaCerts.clear();
7482        saveSettingsLocked(userId);
7483        clearUserPoliciesLocked(userId);
7484        mOwners.removeProfileOwner(userId);
7485        mOwners.writeProfileOwner(userId);
7486        deleteTransferOwnershipBundleLocked(userId);
7487    }
7488
7489    @Override
7490    public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
7491        Preconditions.checkNotNull(who, "ComponentName is null");
7492        if (!mHasFeature) {
7493            return;
7494        }
7495
7496        synchronized (this) {
7497            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7498            long token = mInjector.binderClearCallingIdentity();
7499            try {
7500                mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
7501            } finally {
7502                mInjector.binderRestoreCallingIdentity(token);
7503            }
7504        }
7505    }
7506
7507    @Override
7508    public CharSequence getDeviceOwnerLockScreenInfo() {
7509        return mLockPatternUtils.getDeviceOwnerInfo();
7510    }
7511
7512    private void clearUserPoliciesLocked(int userId) {
7513        // Reset some of the user-specific policies.
7514        final DevicePolicyData policy = getUserData(userId);
7515        policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
7516        // Clear delegations.
7517        policy.mDelegationMap.clear();
7518        policy.mStatusBarDisabled = false;
7519        policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
7520        policy.mAffiliationIds.clear();
7521        policy.mLockTaskPackages.clear();
7522        updateLockTaskPackagesLocked(policy.mLockTaskPackages, userId);
7523        policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
7524        saveSettingsLocked(userId);
7525
7526        try {
7527            mIPackageManager.updatePermissionFlagsForAllApps(
7528                    PackageManager.FLAG_PERMISSION_POLICY_FIXED,
7529                    0  /* flagValues */, userId);
7530            pushUserRestrictions(userId);
7531        } catch (RemoteException re) {
7532            // Shouldn't happen.
7533        }
7534    }
7535
7536    @Override
7537    public boolean hasUserSetupCompleted() {
7538        return hasUserSetupCompleted(UserHandle.getCallingUserId());
7539    }
7540
7541    // This checks only if the Setup Wizard has run.  Since Wear devices pair before
7542    // completing Setup Wizard, and pairing involves transferring user data, calling
7543    // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
7544    private boolean hasUserSetupCompleted(int userHandle) {
7545        if (!mHasFeature) {
7546            return true;
7547        }
7548        return getUserData(userHandle).mUserSetupComplete;
7549    }
7550
7551    private boolean hasPaired(int userHandle) {
7552        if (!mHasFeature) {
7553            return true;
7554        }
7555        return getUserData(userHandle).mPaired;
7556    }
7557
7558    @Override
7559    public int getUserProvisioningState() {
7560        if (!mHasFeature) {
7561            return DevicePolicyManager.STATE_USER_UNMANAGED;
7562        }
7563        int userHandle = mInjector.userHandleGetCallingUserId();
7564        return getUserProvisioningState(userHandle);
7565    }
7566
7567    private int getUserProvisioningState(int userHandle) {
7568        return getUserData(userHandle).mUserProvisioningState;
7569    }
7570
7571    @Override
7572    public void setUserProvisioningState(int newState, int userHandle) {
7573        if (!mHasFeature) {
7574            return;
7575        }
7576
7577        if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
7578                && getManagedUserId(userHandle) == -1) {
7579            // No managed device, user or profile, so setting provisioning state makes no sense.
7580            throw new IllegalStateException("Not allowed to change provisioning state unless a "
7581                      + "device or profile owner is set.");
7582        }
7583
7584        synchronized (this) {
7585            boolean transitionCheckNeeded = true;
7586
7587            // Calling identity/permission checks.
7588            if (isAdb()) {
7589                // ADB shell can only move directly from un-managed to finalized as part of directly
7590                // setting profile-owner or device-owner.
7591                if (getUserProvisioningState(userHandle) !=
7592                        DevicePolicyManager.STATE_USER_UNMANAGED
7593                        || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
7594                    throw new IllegalStateException("Not allowed to change provisioning state "
7595                            + "unless current provisioning state is unmanaged, and new state is "
7596                            + "finalized.");
7597                }
7598                transitionCheckNeeded = false;
7599            } else {
7600                // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
7601                enforceCanManageProfileAndDeviceOwners();
7602            }
7603
7604            final DevicePolicyData policyData = getUserData(userHandle);
7605            if (transitionCheckNeeded) {
7606                // Optional state transition check for non-ADB case.
7607                checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
7608            }
7609            policyData.mUserProvisioningState = newState;
7610            saveSettingsLocked(userHandle);
7611        }
7612    }
7613
7614    private void checkUserProvisioningStateTransition(int currentState, int newState) {
7615        // Valid transitions for normal use-cases.
7616        switch (currentState) {
7617            case DevicePolicyManager.STATE_USER_UNMANAGED:
7618                // Can move to any state from unmanaged (except itself as an edge case)..
7619                if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
7620                    return;
7621                }
7622                break;
7623            case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
7624            case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
7625                // Can only move to finalized from these states.
7626                if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
7627                    return;
7628                }
7629                break;
7630            case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
7631                // Current user has a managed-profile, but current user is not managed, so
7632                // rather than moving to finalized state, go back to unmanaged once
7633                // profile provisioning is complete.
7634                if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
7635                    return;
7636                }
7637                break;
7638            case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
7639                // Cannot transition out of finalized.
7640                break;
7641        }
7642
7643        // Didn't meet any of the accepted state transition checks above, throw appropriate error.
7644        throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
7645                + "from state [" + currentState + "]");
7646    }
7647
7648    @Override
7649    public void setProfileEnabled(ComponentName who) {
7650        if (!mHasFeature) {
7651            return;
7652        }
7653        Preconditions.checkNotNull(who, "ComponentName is null");
7654        synchronized (this) {
7655            // Check if this is the profile owner who is calling
7656            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7657            final int userId = UserHandle.getCallingUserId();
7658            enforceManagedProfile(userId, "enable the profile");
7659            // Check if the profile is already enabled.
7660            UserInfo managedProfile = getUserInfo(userId);
7661            if (managedProfile.isEnabled()) {
7662                Slog.e(LOG_TAG,
7663                        "setProfileEnabled is called when the profile is already enabled");
7664                return;
7665            }
7666            long id = mInjector.binderClearCallingIdentity();
7667            try {
7668                mUserManager.setUserEnabled(userId);
7669                UserInfo parent = mUserManager.getProfileParent(userId);
7670                Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
7671                intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
7672                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
7673                        Intent.FLAG_RECEIVER_FOREGROUND);
7674                mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
7675            } finally {
7676                mInjector.binderRestoreCallingIdentity(id);
7677            }
7678        }
7679    }
7680
7681    @Override
7682    public void setProfileName(ComponentName who, String profileName) {
7683        Preconditions.checkNotNull(who, "ComponentName is null");
7684        int userId = UserHandle.getCallingUserId();
7685        // Check if this is the profile owner (includes device owner).
7686        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7687
7688        long id = mInjector.binderClearCallingIdentity();
7689        try {
7690            mUserManager.setUserName(userId, profileName);
7691        } finally {
7692            mInjector.binderRestoreCallingIdentity(id);
7693        }
7694    }
7695
7696    @Override
7697    public ComponentName getProfileOwner(int userHandle) {
7698        if (!mHasFeature) {
7699            return null;
7700        }
7701
7702        synchronized (this) {
7703            return mOwners.getProfileOwnerComponent(userHandle);
7704        }
7705    }
7706
7707    // Returns the active profile owner for this user or null if the current user has no
7708    // profile owner.
7709    @VisibleForTesting
7710    ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
7711        ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
7712        if (profileOwner == null) {
7713            return null;
7714        }
7715        DevicePolicyData policy = getUserData(userHandle);
7716        final int n = policy.mAdminList.size();
7717        for (int i = 0; i < n; i++) {
7718            ActiveAdmin admin = policy.mAdminList.get(i);
7719            if (profileOwner.equals(admin.info.getComponent())) {
7720                return admin;
7721            }
7722        }
7723        return null;
7724    }
7725
7726    @Override
7727    public String getProfileOwnerName(int userHandle) {
7728        if (!mHasFeature) {
7729            return null;
7730        }
7731        enforceManageUsers();
7732        ComponentName profileOwner = getProfileOwner(userHandle);
7733        if (profileOwner == null) {
7734            return null;
7735        }
7736        return getApplicationLabel(profileOwner.getPackageName(), userHandle);
7737    }
7738
7739    /**
7740     * Canonical name for a given package.
7741     */
7742    private String getApplicationLabel(String packageName, int userHandle) {
7743        long token = mInjector.binderClearCallingIdentity();
7744        try {
7745            final Context userContext;
7746            try {
7747                UserHandle handle = new UserHandle(userHandle);
7748                userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
7749            } catch (PackageManager.NameNotFoundException nnfe) {
7750                Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
7751                return null;
7752            }
7753            ApplicationInfo appInfo = userContext.getApplicationInfo();
7754            CharSequence result = null;
7755            if (appInfo != null) {
7756                PackageManager pm = userContext.getPackageManager();
7757                result = pm.getApplicationLabel(appInfo);
7758            }
7759            return result != null ? result.toString() : null;
7760        } finally {
7761            mInjector.binderRestoreCallingIdentity(token);
7762        }
7763    }
7764
7765    /**
7766     * Calls wtfStack() if called with the DPMS lock held.
7767     */
7768    private void wtfIfInLock() {
7769        if (Thread.holdsLock(this)) {
7770            Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
7771        }
7772    }
7773
7774    /**
7775     * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7776     * permission.
7777     * The profile owner can only be set before the user setup phase has completed,
7778     * except for:
7779     * - SYSTEM_UID
7780     * - adb unless hasIncompatibleAccountsOrNonAdb is true.
7781     */
7782    private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle,
7783            boolean hasIncompatibleAccountsOrNonAdb) {
7784        UserInfo info = getUserInfo(userHandle);
7785        if (info == null) {
7786            // User doesn't exist.
7787            throw new IllegalArgumentException(
7788                    "Attempted to set profile owner for invalid userId: " + userHandle);
7789        }
7790        if (info.isGuest()) {
7791            throw new IllegalStateException("Cannot set a profile owner on a guest");
7792        }
7793        if (mOwners.hasProfileOwner(userHandle)) {
7794            throw new IllegalStateException("Trying to set the profile owner, but profile owner "
7795                    + "is already set.");
7796        }
7797        if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
7798            throw new IllegalStateException("Trying to set the profile owner, but the user "
7799                    + "already has a device owner.");
7800        }
7801        if (isAdb()) {
7802            if ((mIsWatch || hasUserSetupCompleted(userHandle))
7803                    && hasIncompatibleAccountsOrNonAdb) {
7804                throw new IllegalStateException("Not allowed to set the profile owner because "
7805                        + "there are already some accounts on the profile");
7806            }
7807            return;
7808        }
7809        enforceCanManageProfileAndDeviceOwners();
7810        if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
7811            throw new IllegalStateException("Cannot set the profile owner on a user which is "
7812                    + "already set-up");
7813        }
7814    }
7815
7816    /**
7817     * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7818     * permission.
7819     */
7820    private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId,
7821            boolean hasIncompatibleAccountsOrNonAdb) {
7822        if (!isAdb()) {
7823            enforceCanManageProfileAndDeviceOwners();
7824        }
7825
7826        final int code = checkDeviceOwnerProvisioningPreConditionLocked(
7827                owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb);
7828        switch (code) {
7829            case CODE_OK:
7830                return;
7831            case CODE_HAS_DEVICE_OWNER:
7832                throw new IllegalStateException(
7833                        "Trying to set the device owner, but device owner is already set.");
7834            case CODE_USER_HAS_PROFILE_OWNER:
7835                throw new IllegalStateException("Trying to set the device owner, but the user "
7836                        + "already has a profile owner.");
7837            case CODE_USER_NOT_RUNNING:
7838                throw new IllegalStateException("User not running: " + userId);
7839            case CODE_NOT_SYSTEM_USER:
7840                throw new IllegalStateException("User is not system user");
7841            case CODE_USER_SETUP_COMPLETED:
7842                throw new IllegalStateException(
7843                        "Cannot set the device owner if the device is already set-up");
7844            case CODE_NONSYSTEM_USER_EXISTS:
7845                throw new IllegalStateException("Not allowed to set the device owner because there "
7846                        + "are already several users on the device");
7847            case CODE_ACCOUNTS_NOT_EMPTY:
7848                throw new IllegalStateException("Not allowed to set the device owner because there "
7849                        + "are already some accounts on the device");
7850            case CODE_HAS_PAIRED:
7851                throw new IllegalStateException("Not allowed to set the device owner because this "
7852                        + "device has already paired");
7853            default:
7854                throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code);
7855        }
7856    }
7857
7858    private void enforceUserUnlocked(int userId) {
7859        // Since we're doing this operation on behalf of an app, we only
7860        // want to use the actual "unlocked" state.
7861        Preconditions.checkState(mUserManager.isUserUnlocked(userId),
7862                "User must be running and unlocked");
7863    }
7864
7865    private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
7866        if (parent) {
7867            enforceUserUnlocked(getProfileParentId(userId));
7868        } else {
7869            enforceUserUnlocked(userId);
7870        }
7871    }
7872
7873    private void enforceManageUsers() {
7874        final int callingUid = mInjector.binderGetCallingUid();
7875        if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
7876            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7877        }
7878    }
7879
7880    private void enforceFullCrossUsersPermission(int userHandle) {
7881        enforceSystemUserOrPermissionIfCrossUser(userHandle,
7882                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
7883    }
7884
7885    private void enforceCrossUsersPermission(int userHandle) {
7886        enforceSystemUserOrPermissionIfCrossUser(userHandle,
7887                android.Manifest.permission.INTERACT_ACROSS_USERS);
7888    }
7889
7890    private void enforceSystemUserOrPermission(String permission) {
7891        if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) {
7892            mContext.enforceCallingOrSelfPermission(permission,
7893                    "Must be system or have " + permission + " permission");
7894        }
7895    }
7896
7897    private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) {
7898        if (userHandle < 0) {
7899            throw new IllegalArgumentException("Invalid userId " + userHandle);
7900        }
7901        if (userHandle == mInjector.userHandleGetCallingUserId()) {
7902            return;
7903        }
7904        enforceSystemUserOrPermission(permission);
7905    }
7906
7907    private void enforceManagedProfile(int userHandle, String message) {
7908        if(!isManagedProfile(userHandle)) {
7909            throw new SecurityException("You can not " + message + " outside a managed profile.");
7910        }
7911    }
7912
7913    private void enforceNotManagedProfile(int userHandle, String message) {
7914        if(isManagedProfile(userHandle)) {
7915            throw new SecurityException("You can not " + message + " for a managed profile.");
7916        }
7917    }
7918
7919    private void enforceDeviceOwnerOrManageUsers() {
7920        synchronized (this) {
7921            if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7922                    mInjector.binderGetCallingUid()) != null) {
7923                return;
7924            }
7925        }
7926        enforceManageUsers();
7927    }
7928
7929    private void enforceProfileOwnerOrSystemUser() {
7930        synchronized (this) {
7931            if (getActiveAdminWithPolicyForUidLocked(null,
7932                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7933                            != null) {
7934                return;
7935            }
7936        }
7937        Preconditions.checkState(isCallerWithSystemUid(),
7938                "Only profile owner, device owner and system may call this method.");
7939    }
7940
7941    private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) {
7942        if (userId == mInjector.userHandleGetCallingUserId()) {
7943            synchronized (this) {
7944                if (getActiveAdminWithPolicyForUidLocked(null,
7945                        DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7946                                != null) {
7947                    // Device Owner/Profile Owner may access the user it runs on.
7948                    return;
7949                }
7950            }
7951        }
7952        // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required.
7953        enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
7954    }
7955
7956    private boolean canUserUseLockTaskLocked(int userId) {
7957        if (isUserAffiliatedWithDeviceLocked(userId)) {
7958            return true;
7959        }
7960
7961        // Unaffiliated profile owners are not allowed to use lock when there is a device owner.
7962        if (mOwners.hasDeviceOwner()) {
7963            return false;
7964        }
7965
7966        final ComponentName profileOwner = getProfileOwner(userId);
7967        if (profileOwner == null) {
7968            return false;
7969        }
7970
7971        // Managed profiles are not allowed to use lock task
7972        if (isManagedProfile(userId)) {
7973            return false;
7974        }
7975
7976        return true;
7977    }
7978
7979    private void enforceCanCallLockTaskLocked(ComponentName who) {
7980        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7981        final int userId =  mInjector.userHandleGetCallingUserId();
7982        if (!canUserUseLockTaskLocked(userId)) {
7983            throw new SecurityException("User " + userId + " is not allowed to use lock task");
7984        }
7985    }
7986
7987    private void ensureCallerPackage(@Nullable String packageName) {
7988        if (packageName == null) {
7989            Preconditions.checkState(isCallerWithSystemUid(),
7990                    "Only caller can omit package name");
7991        } else {
7992            final int callingUid = mInjector.binderGetCallingUid();
7993            final int userId = mInjector.userHandleGetCallingUserId();
7994            try {
7995                final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
7996                        packageName, 0, userId);
7997                Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
7998            } catch (RemoteException e) {
7999                // Shouldn't happen
8000            }
8001        }
8002    }
8003
8004    private boolean isCallerWithSystemUid() {
8005        return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
8006    }
8007
8008    protected int getProfileParentId(int userHandle) {
8009        final long ident = mInjector.binderClearCallingIdentity();
8010        try {
8011            UserInfo parentUser = mUserManager.getProfileParent(userHandle);
8012            return parentUser != null ? parentUser.id : userHandle;
8013        } finally {
8014            mInjector.binderRestoreCallingIdentity(ident);
8015        }
8016    }
8017
8018    private int getCredentialOwner(int userHandle, boolean parent) {
8019        final long ident = mInjector.binderClearCallingIdentity();
8020        try {
8021            if (parent) {
8022                UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
8023                if (parentProfile != null) {
8024                    userHandle = parentProfile.id;
8025                }
8026            }
8027            return mUserManager.getCredentialOwnerProfile(userHandle);
8028        } finally {
8029            mInjector.binderRestoreCallingIdentity(ident);
8030        }
8031    }
8032
8033    private boolean isManagedProfile(int userHandle) {
8034        final UserInfo user = getUserInfo(userHandle);
8035        return user != null && user.isManagedProfile();
8036    }
8037
8038    private void enableIfNecessary(String packageName, int userId) {
8039        try {
8040            final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
8041                    PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId);
8042            if (ai.enabledSetting
8043                    == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
8044                mIPackageManager.setApplicationEnabledSetting(packageName,
8045                        PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
8046                        PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
8047            }
8048        } catch (RemoteException e) {
8049        }
8050    }
8051
8052    @Override
8053    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
8054        if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
8055
8056        synchronized (this) {
8057            pw.println("Current Device Policy Manager state:");
8058
8059            mOwners.dump("  ", pw);
8060            mDeviceAdminServiceController.dump("  ", pw);
8061            int userCount = mUserData.size();
8062            for (int u = 0; u < userCount; u++) {
8063                DevicePolicyData policy = getUserData(mUserData.keyAt(u));
8064                pw.println();
8065                pw.println("  Enabled Device Admins (User " + policy.mUserHandle
8066                        + ", provisioningState: " + policy.mUserProvisioningState + "):");
8067                final int N = policy.mAdminList.size();
8068                for (int i=0; i<N; i++) {
8069                    ActiveAdmin ap = policy.mAdminList.get(i);
8070                    if (ap != null) {
8071                        pw.print("    "); pw.print(ap.info.getComponent().flattenToShortString());
8072                                pw.println(":");
8073                        ap.dump("      ", pw);
8074                    }
8075                }
8076                if (!policy.mRemovingAdmins.isEmpty()) {
8077                    pw.println("    Removing Device Admins (User " + policy.mUserHandle + "): "
8078                            + policy.mRemovingAdmins);
8079                }
8080
8081                pw.println(" ");
8082                pw.print("    mPasswordOwner="); pw.println(policy.mPasswordOwner);
8083            }
8084            pw.println();
8085            mConstants.dump("  ", pw);
8086            pw.println();
8087            pw.println("  Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
8088        }
8089    }
8090
8091    private String getEncryptionStatusName(int encryptionStatus) {
8092        switch (encryptionStatus) {
8093            case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
8094                return "inactive";
8095            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
8096                return "block default key";
8097            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
8098                return "block";
8099            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
8100                return "per-user";
8101            case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
8102                return "unsupported";
8103            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
8104                return "activating";
8105            default:
8106                return "unknown";
8107        }
8108    }
8109
8110    @Override
8111    public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
8112            ComponentName activity) {
8113        Preconditions.checkNotNull(who, "ComponentName is null");
8114        final int userHandle = UserHandle.getCallingUserId();
8115        synchronized (this) {
8116            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8117
8118            long id = mInjector.binderClearCallingIdentity();
8119            try {
8120                mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
8121                mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
8122            } catch (RemoteException re) {
8123                // Shouldn't happen
8124            } finally {
8125                mInjector.binderRestoreCallingIdentity(id);
8126            }
8127        }
8128    }
8129
8130    @Override
8131    public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
8132        Preconditions.checkNotNull(who, "ComponentName is null");
8133        final int userHandle = UserHandle.getCallingUserId();
8134        synchronized (this) {
8135            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8136
8137            long id = mInjector.binderClearCallingIdentity();
8138            try {
8139                mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
8140                mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
8141            } catch (RemoteException re) {
8142                // Shouldn't happen
8143            } finally {
8144                mInjector.binderRestoreCallingIdentity(id);
8145            }
8146        }
8147    }
8148
8149    @Override
8150    public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
8151            String packageName) {
8152        try {
8153            setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
8154        } catch (IllegalArgumentException e) {
8155            return false;
8156        }
8157        return true;
8158    }
8159
8160    @Override
8161    public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
8162        final List<String> delegatePackages = getDelegatePackages(admin,
8163                DELEGATION_APP_RESTRICTIONS);
8164        return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
8165    }
8166
8167    @Override
8168    public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
8169        return isCallerDelegate(callerPackage, DELEGATION_APP_RESTRICTIONS);
8170    }
8171
8172    @Override
8173    public void setApplicationRestrictions(ComponentName who, String callerPackage,
8174            String packageName, Bundle settings) {
8175        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8176                DELEGATION_APP_RESTRICTIONS);
8177
8178        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
8179        final long id = mInjector.binderClearCallingIdentity();
8180        try {
8181            mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
8182        } finally {
8183            mInjector.binderRestoreCallingIdentity(id);
8184        }
8185    }
8186
8187    @Override
8188    public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
8189            PersistableBundle args, boolean parent) {
8190        if (!mHasFeature) {
8191            return;
8192        }
8193        Preconditions.checkNotNull(admin, "admin is null");
8194        Preconditions.checkNotNull(agent, "agent is null");
8195        final int userHandle = UserHandle.getCallingUserId();
8196        synchronized (this) {
8197            ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
8198                    DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
8199            ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
8200            saveSettingsLocked(userHandle);
8201        }
8202    }
8203
8204    @Override
8205    public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
8206            ComponentName agent, int userHandle, boolean parent) {
8207        if (!mHasFeature) {
8208            return null;
8209        }
8210        Preconditions.checkNotNull(agent, "agent null");
8211        enforceFullCrossUsersPermission(userHandle);
8212
8213        synchronized (this) {
8214            final String componentName = agent.flattenToString();
8215            if (admin != null) {
8216                final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
8217                if (ap == null) return null;
8218                TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
8219                if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
8220                List<PersistableBundle> result = new ArrayList<>();
8221                result.add(trustAgentInfo.options);
8222                return result;
8223            }
8224
8225            // Return strictest policy for this user and profiles that are visible from this user.
8226            List<PersistableBundle> result = null;
8227            // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
8228            // of the options. If any admin doesn't have options, discard options for the rest
8229            // and return null.
8230            List<ActiveAdmin> admins =
8231                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
8232            boolean allAdminsHaveOptions = true;
8233            final int N = admins.size();
8234            for (int i = 0; i < N; i++) {
8235                final ActiveAdmin active = admins.get(i);
8236
8237                final boolean disablesTrust = (active.disabledKeyguardFeatures
8238                        & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
8239                final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
8240                if (info != null && info.options != null && !info.options.isEmpty()) {
8241                    if (disablesTrust) {
8242                        if (result == null) {
8243                            result = new ArrayList<>();
8244                        }
8245                        result.add(info.options);
8246                    } else {
8247                        Log.w(LOG_TAG, "Ignoring admin " + active.info
8248                                + " because it has trust options but doesn't declare "
8249                                + "KEYGUARD_DISABLE_TRUST_AGENTS");
8250                    }
8251                } else if (disablesTrust) {
8252                    allAdminsHaveOptions = false;
8253                    break;
8254                }
8255            }
8256            return allAdminsHaveOptions ? result : null;
8257        }
8258    }
8259
8260    @Override
8261    public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
8262        Preconditions.checkNotNull(who, "ComponentName is null");
8263        synchronized (this) {
8264            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8265
8266            int userHandle = UserHandle.getCallingUserId();
8267            DevicePolicyData userData = getUserData(userHandle);
8268            userData.mRestrictionsProvider = permissionProvider;
8269            saveSettingsLocked(userHandle);
8270        }
8271    }
8272
8273    @Override
8274    public ComponentName getRestrictionsProvider(int userHandle) {
8275        synchronized (this) {
8276            if (!isCallerWithSystemUid()) {
8277                throw new SecurityException("Only the system can query the permission provider");
8278            }
8279            DevicePolicyData userData = getUserData(userHandle);
8280            return userData != null ? userData.mRestrictionsProvider : null;
8281        }
8282    }
8283
8284    @Override
8285    public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
8286        Preconditions.checkNotNull(who, "ComponentName is null");
8287        int callingUserId = UserHandle.getCallingUserId();
8288        synchronized (this) {
8289            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8290
8291            long id = mInjector.binderClearCallingIdentity();
8292            try {
8293                UserInfo parent = mUserManager.getProfileParent(callingUserId);
8294                if (parent == null) {
8295                    Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
8296                            + "parent");
8297                    return;
8298                }
8299                if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
8300                    mIPackageManager.addCrossProfileIntentFilter(
8301                            filter, who.getPackageName(), callingUserId, parent.id, 0);
8302                }
8303                if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
8304                    mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
8305                            parent.id, callingUserId, 0);
8306                }
8307            } catch (RemoteException re) {
8308                // Shouldn't happen
8309            } finally {
8310                mInjector.binderRestoreCallingIdentity(id);
8311            }
8312        }
8313    }
8314
8315    @Override
8316    public void clearCrossProfileIntentFilters(ComponentName who) {
8317        Preconditions.checkNotNull(who, "ComponentName is null");
8318        int callingUserId = UserHandle.getCallingUserId();
8319        synchronized (this) {
8320            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8321            long id = mInjector.binderClearCallingIdentity();
8322            try {
8323                UserInfo parent = mUserManager.getProfileParent(callingUserId);
8324                if (parent == null) {
8325                    Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
8326                            + "parent");
8327                    return;
8328                }
8329                // Removing those that go from the managed profile to the parent.
8330                mIPackageManager.clearCrossProfileIntentFilters(
8331                        callingUserId, who.getPackageName());
8332                // And those that go from the parent to the managed profile.
8333                // If we want to support multiple managed profiles, we will have to only remove
8334                // those that have callingUserId as their target.
8335                mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
8336            } catch (RemoteException re) {
8337                // Shouldn't happen
8338            } finally {
8339                mInjector.binderRestoreCallingIdentity(id);
8340            }
8341        }
8342    }
8343
8344    /**
8345     * @return true if all packages in enabledPackages are either in the list
8346     * permittedList or are a system app.
8347     */
8348    private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
8349            List<String> permittedList, int userIdToCheck) {
8350        long id = mInjector.binderClearCallingIdentity();
8351        try {
8352            // If we have an enabled packages list for a managed profile the packages
8353            // we should check are installed for the parent user.
8354            UserInfo user = getUserInfo(userIdToCheck);
8355            if (user.isManagedProfile()) {
8356                userIdToCheck = user.profileGroupId;
8357            }
8358
8359            for (String enabledPackage : enabledPackages) {
8360                boolean systemService = false;
8361                try {
8362                    ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
8363                            enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
8364                            userIdToCheck);
8365                    systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
8366                } catch (RemoteException e) {
8367                    Log.i(LOG_TAG, "Can't talk to package managed", e);
8368                }
8369                if (!systemService && !permittedList.contains(enabledPackage)) {
8370                    return false;
8371                }
8372            }
8373        } finally {
8374            mInjector.binderRestoreCallingIdentity(id);
8375        }
8376        return true;
8377    }
8378
8379    private AccessibilityManager getAccessibilityManagerForUser(int userId) {
8380        // Not using AccessibilityManager.getInstance because that guesses
8381        // at the user you require based on callingUid and caches for a given
8382        // process.
8383        IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
8384        IAccessibilityManager service = iBinder == null
8385                ? null : IAccessibilityManager.Stub.asInterface(iBinder);
8386        return new AccessibilityManager(mContext, service, userId);
8387    }
8388
8389    @Override
8390    public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
8391        if (!mHasFeature) {
8392            return false;
8393        }
8394        Preconditions.checkNotNull(who, "ComponentName is null");
8395
8396        if (packageList != null) {
8397            int userId = UserHandle.getCallingUserId();
8398            List<AccessibilityServiceInfo> enabledServices = null;
8399            long id = mInjector.binderClearCallingIdentity();
8400            try {
8401                UserInfo user = getUserInfo(userId);
8402                if (user.isManagedProfile()) {
8403                    userId = user.profileGroupId;
8404                }
8405                AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
8406                enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
8407                        AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
8408            } finally {
8409                mInjector.binderRestoreCallingIdentity(id);
8410            }
8411
8412            if (enabledServices != null) {
8413                List<String> enabledPackages = new ArrayList<String>();
8414                for (AccessibilityServiceInfo service : enabledServices) {
8415                    enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
8416                }
8417                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
8418                        userId)) {
8419                    Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
8420                            + "because it contains already enabled accesibility services.");
8421                    return false;
8422                }
8423            }
8424        }
8425
8426        synchronized (this) {
8427            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8428                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8429            admin.permittedAccessiblityServices = packageList;
8430            saveSettingsLocked(UserHandle.getCallingUserId());
8431        }
8432        return true;
8433    }
8434
8435    @Override
8436    public List getPermittedAccessibilityServices(ComponentName who) {
8437        if (!mHasFeature) {
8438            return null;
8439        }
8440        Preconditions.checkNotNull(who, "ComponentName is null");
8441
8442        synchronized (this) {
8443            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8444                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8445            return admin.permittedAccessiblityServices;
8446        }
8447    }
8448
8449    @Override
8450    public List getPermittedAccessibilityServicesForUser(int userId) {
8451        if (!mHasFeature) {
8452            return null;
8453        }
8454        synchronized (this) {
8455            List<String> result = null;
8456            // If we have multiple profiles we return the intersection of the
8457            // permitted lists. This can happen in cases where we have a device
8458            // and profile owner.
8459            int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
8460            for (int profileId : profileIds) {
8461                // Just loop though all admins, only device or profiles
8462                // owners can have permitted lists set.
8463                DevicePolicyData policy = getUserDataUnchecked(profileId);
8464                final int N = policy.mAdminList.size();
8465                for (int j = 0; j < N; j++) {
8466                    ActiveAdmin admin = policy.mAdminList.get(j);
8467                    List<String> fromAdmin = admin.permittedAccessiblityServices;
8468                    if (fromAdmin != null) {
8469                        if (result == null) {
8470                            result = new ArrayList<>(fromAdmin);
8471                        } else {
8472                            result.retainAll(fromAdmin);
8473                        }
8474                    }
8475                }
8476            }
8477
8478            // If we have a permitted list add all system accessibility services.
8479            if (result != null) {
8480                long id = mInjector.binderClearCallingIdentity();
8481                try {
8482                    UserInfo user = getUserInfo(userId);
8483                    if (user.isManagedProfile()) {
8484                        userId = user.profileGroupId;
8485                    }
8486                    AccessibilityManager accessibilityManager =
8487                            getAccessibilityManagerForUser(userId);
8488                    List<AccessibilityServiceInfo> installedServices =
8489                            accessibilityManager.getInstalledAccessibilityServiceList();
8490
8491                    if (installedServices != null) {
8492                        for (AccessibilityServiceInfo service : installedServices) {
8493                            ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
8494                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
8495                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8496                                result.add(serviceInfo.packageName);
8497                            }
8498                        }
8499                    }
8500                } finally {
8501                    mInjector.binderRestoreCallingIdentity(id);
8502                }
8503            }
8504
8505            return result;
8506        }
8507    }
8508
8509    @Override
8510    public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
8511            int userHandle) {
8512        if (!mHasFeature) {
8513            return true;
8514        }
8515        Preconditions.checkNotNull(who, "ComponentName is null");
8516        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
8517        if (!isCallerWithSystemUid()){
8518            throw new SecurityException(
8519                    "Only the system can query if an accessibility service is disabled by admin");
8520        }
8521        synchronized (this) {
8522            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8523            if (admin == null) {
8524                return false;
8525            }
8526            if (admin.permittedAccessiblityServices == null) {
8527                return true;
8528            }
8529            return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8530                    admin.permittedAccessiblityServices, userHandle);
8531        }
8532    }
8533
8534    private boolean checkCallerIsCurrentUserOrProfile() {
8535        final int callingUserId = UserHandle.getCallingUserId();
8536        final long token = mInjector.binderClearCallingIdentity();
8537        try {
8538            UserInfo currentUser;
8539            UserInfo callingUser = getUserInfo(callingUserId);
8540            try {
8541                currentUser = mInjector.getIActivityManager().getCurrentUser();
8542            } catch (RemoteException e) {
8543                Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
8544                return false;
8545            }
8546
8547            if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
8548                Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
8549                        + "of a user that isn't the foreground user.");
8550                return false;
8551            }
8552            if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
8553                Slog.e(LOG_TAG, "Cannot set permitted input methods "
8554                        + "of a user that isn't the foreground user.");
8555                return false;
8556            }
8557        } finally {
8558            mInjector.binderRestoreCallingIdentity(token);
8559        }
8560        return true;
8561    }
8562
8563    @Override
8564    public boolean setPermittedInputMethods(ComponentName who, List packageList) {
8565        if (!mHasFeature) {
8566            return false;
8567        }
8568        Preconditions.checkNotNull(who, "ComponentName is null");
8569
8570        // TODO When InputMethodManager supports per user calls remove
8571        //      this restriction.
8572        if (!checkCallerIsCurrentUserOrProfile()) {
8573            return false;
8574        }
8575
8576        final int callingUserId = mInjector.userHandleGetCallingUserId();
8577        if (packageList != null) {
8578            // InputMethodManager fetches input methods for current user.
8579            // So this can only be set when calling user is the current user
8580            // or parent is current user in case of managed profiles.
8581            InputMethodManager inputMethodManager =
8582                    mContext.getSystemService(InputMethodManager.class);
8583            List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
8584
8585            if (enabledImes != null) {
8586                List<String> enabledPackages = new ArrayList<String>();
8587                for (InputMethodInfo ime : enabledImes) {
8588                    enabledPackages.add(ime.getPackageName());
8589                }
8590                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
8591                        callingUserId)) {
8592                    Slog.e(LOG_TAG, "Cannot set permitted input methods, "
8593                            + "because it contains already enabled input method.");
8594                    return false;
8595                }
8596            }
8597        }
8598
8599        synchronized (this) {
8600            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8601                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8602            admin.permittedInputMethods = packageList;
8603            saveSettingsLocked(callingUserId);
8604        }
8605        return true;
8606    }
8607
8608    @Override
8609    public List getPermittedInputMethods(ComponentName who) {
8610        if (!mHasFeature) {
8611            return null;
8612        }
8613        Preconditions.checkNotNull(who, "ComponentName is null");
8614
8615        synchronized (this) {
8616            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8617                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8618            return admin.permittedInputMethods;
8619        }
8620    }
8621
8622    @Override
8623    public List getPermittedInputMethodsForCurrentUser() {
8624        UserInfo currentUser;
8625        try {
8626            currentUser = mInjector.getIActivityManager().getCurrentUser();
8627        } catch (RemoteException e) {
8628            Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
8629            // Activity managed is dead, just allow all IMEs
8630            return null;
8631        }
8632
8633        int userId = currentUser.id;
8634        synchronized (this) {
8635            List<String> result = null;
8636            // If we have multiple profiles we return the intersection of the
8637            // permitted lists. This can happen in cases where we have a device
8638            // and profile owner.
8639            int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
8640            for (int profileId : profileIds) {
8641                // Just loop though all admins, only device or profiles
8642                // owners can have permitted lists set.
8643                DevicePolicyData policy = getUserDataUnchecked(profileId);
8644                final int N = policy.mAdminList.size();
8645                for (int j = 0; j < N; j++) {
8646                    ActiveAdmin admin = policy.mAdminList.get(j);
8647                    List<String> fromAdmin = admin.permittedInputMethods;
8648                    if (fromAdmin != null) {
8649                        if (result == null) {
8650                            result = new ArrayList<String>(fromAdmin);
8651                        } else {
8652                            result.retainAll(fromAdmin);
8653                        }
8654                    }
8655                }
8656            }
8657
8658            // If we have a permitted list add all system input methods.
8659            if (result != null) {
8660                InputMethodManager inputMethodManager =
8661                        mContext.getSystemService(InputMethodManager.class);
8662                List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
8663                long id = mInjector.binderClearCallingIdentity();
8664                try {
8665                    if (imes != null) {
8666                        for (InputMethodInfo ime : imes) {
8667                            ServiceInfo serviceInfo = ime.getServiceInfo();
8668                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
8669                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8670                                result.add(serviceInfo.packageName);
8671                            }
8672                        }
8673                    }
8674                } finally {
8675                    mInjector.binderRestoreCallingIdentity(id);
8676                }
8677            }
8678            return result;
8679        }
8680    }
8681
8682    @Override
8683    public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
8684            int userHandle) {
8685        if (!mHasFeature) {
8686            return true;
8687        }
8688        Preconditions.checkNotNull(who, "ComponentName is null");
8689        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
8690        if (!isCallerWithSystemUid()) {
8691            throw new SecurityException(
8692                    "Only the system can query if an input method is disabled by admin");
8693        }
8694        synchronized (this) {
8695            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8696            if (admin == null) {
8697                return false;
8698            }
8699            if (admin.permittedInputMethods == null) {
8700                return true;
8701            }
8702            return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8703                    admin.permittedInputMethods, userHandle);
8704        }
8705    }
8706
8707    @Override
8708    public boolean setPermittedCrossProfileNotificationListeners(
8709            ComponentName who, List<String> packageList) {
8710        if (!mHasFeature) {
8711            return false;
8712        }
8713        Preconditions.checkNotNull(who, "ComponentName is null");
8714
8715        final int callingUserId = mInjector.userHandleGetCallingUserId();
8716        if (!isManagedProfile(callingUserId)) {
8717            return false;
8718        }
8719
8720        synchronized (this) {
8721            ActiveAdmin admin = getActiveAdminForCallerLocked(
8722                    who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8723            admin.permittedNotificationListeners = packageList;
8724            saveSettingsLocked(callingUserId);
8725        }
8726        return true;
8727    }
8728
8729    @Override
8730    public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) {
8731        if (!mHasFeature) {
8732            return null;
8733        }
8734        Preconditions.checkNotNull(who, "ComponentName is null");
8735
8736        synchronized (this) {
8737            ActiveAdmin admin = getActiveAdminForCallerLocked(
8738                    who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8739            return admin.permittedNotificationListeners;
8740        }
8741    }
8742
8743    @Override
8744    public boolean isNotificationListenerServicePermitted(String packageName, int userId) {
8745        if (!mHasFeature) {
8746            return true;
8747        }
8748
8749        Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty");
8750        if (!isCallerWithSystemUid()) {
8751            throw new SecurityException(
8752                    "Only the system can query if a notification listener service is permitted");
8753        }
8754        synchronized (this) {
8755            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
8756            if (profileOwner == null || profileOwner.permittedNotificationListeners == null) {
8757                return true;
8758            }
8759            return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8760                    profileOwner.permittedNotificationListeners, userId);
8761
8762        }
8763    }
8764
8765    private void maybeSendAdminEnabledBroadcastLocked(int userHandle) {
8766        DevicePolicyData policyData = getUserData(userHandle);
8767        if (policyData.mAdminBroadcastPending) {
8768            // Send the initialization data to profile owner and delete the data
8769            ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
8770            boolean clearInitBundle = true;
8771            if (admin != null) {
8772                PersistableBundle initBundle = policyData.mInitBundle;
8773                clearInitBundle = sendAdminCommandLocked(admin,
8774                        DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
8775                        initBundle == null ? null : new Bundle(initBundle),
8776                        null /* result receiver */,
8777                        true /* send in foreground */);
8778            }
8779            if (clearInitBundle) {
8780                // If there's no admin or we've successfully called the admin, clear the init bundle
8781                // otherwise, keep it around
8782                policyData.mInitBundle = null;
8783                policyData.mAdminBroadcastPending = false;
8784                saveSettingsLocked(userHandle);
8785            }
8786        }
8787    }
8788
8789    @Override
8790    public UserHandle createAndManageUser(ComponentName admin, String name,
8791            ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
8792        Preconditions.checkNotNull(admin, "admin is null");
8793        Preconditions.checkNotNull(profileOwner, "profileOwner is null");
8794        if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
8795            throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
8796                    + admin + " are not in the same package");
8797        }
8798        // Only allow the system user to use this method
8799        if (!mInjector.binderGetCallingUserHandle().isSystem()) {
8800            throw new SecurityException("createAndManageUser was called from non-system user");
8801        }
8802        final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0;
8803        final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0
8804                && UserManager.isDeviceInDemoMode(mContext);
8805        final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0;
8806        // Create user.
8807        UserHandle user = null;
8808        synchronized (this) {
8809            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8810
8811            final long id = mInjector.binderClearCallingIdentity();
8812            try {
8813                int userInfoFlags = 0;
8814                if (ephemeral) {
8815                    userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
8816                }
8817                if (demo) {
8818                    userInfoFlags |= UserInfo.FLAG_DEMO;
8819                }
8820                String[] disallowedPackages = null;
8821                if (!leaveAllSystemAppsEnabled) {
8822                    disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin,
8823                            UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray(
8824                            new String[0]);
8825                }
8826                UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
8827                        userInfoFlags, disallowedPackages);
8828                if (userInfo != null) {
8829                    user = userInfo.getUserHandle();
8830                }
8831            } finally {
8832                mInjector.binderRestoreCallingIdentity(id);
8833            }
8834        }
8835        if (user == null) {
8836            return null;
8837        }
8838
8839        final int userHandle = user.getIdentifier();
8840        final Intent intent = new Intent(DevicePolicyManager.ACTION_MANAGED_USER_CREATED)
8841                .putExtra(Intent.EXTRA_USER_HANDLE, userHandle)
8842                .putExtra(
8843                        DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED,
8844                        leaveAllSystemAppsEnabled)
8845                .setPackage(MANAGED_PROVISIONING_PKG)
8846                .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8847        mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
8848
8849        final long id = mInjector.binderClearCallingIdentity();
8850        try {
8851            final String adminPkg = admin.getPackageName();
8852            try {
8853                // Install the profile owner if not present.
8854                if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
8855                    mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle,
8856                            0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8857                }
8858            } catch (RemoteException e) {
8859                // Does not happen, same process
8860            }
8861
8862            // Set admin.
8863            setActiveAdmin(profileOwner, true, userHandle);
8864            final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
8865            setProfileOwner(profileOwner, ownerName, userHandle);
8866
8867            synchronized (this) {
8868                DevicePolicyData policyData = getUserData(userHandle);
8869                policyData.mInitBundle = adminExtras;
8870                policyData.mAdminBroadcastPending = true;
8871                saveSettingsLocked(userHandle);
8872            }
8873
8874            if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
8875                Settings.Secure.putIntForUser(mContext.getContentResolver(),
8876                        Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
8877            }
8878
8879            return user;
8880        } catch (Throwable re) {
8881            mUserManager.removeUser(userHandle);
8882            return null;
8883        } finally {
8884            mInjector.binderRestoreCallingIdentity(id);
8885        }
8886    }
8887
8888    @Override
8889    public boolean removeUser(ComponentName who, UserHandle userHandle) {
8890        Preconditions.checkNotNull(who, "ComponentName is null");
8891        Preconditions.checkNotNull(userHandle, "UserHandle is null");
8892
8893        synchronized (this) {
8894            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8895        }
8896
8897        final int callingUserId = mInjector.userHandleGetCallingUserId();
8898        final long id = mInjector.binderClearCallingIdentity();
8899        try {
8900            String restriction = isManagedProfile(userHandle.getIdentifier())
8901                    ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
8902                    : UserManager.DISALLOW_REMOVE_USER;
8903            if (isAdminAffectedByRestriction(who, restriction, callingUserId)) {
8904                Log.w(LOG_TAG, "The device owner cannot remove a user because "
8905                        + restriction + " is enabled, and was not set by the device owner");
8906                return false;
8907            }
8908            return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
8909        } finally {
8910            mInjector.binderRestoreCallingIdentity(id);
8911        }
8912    }
8913
8914    private boolean isAdminAffectedByRestriction(
8915            ComponentName admin, String userRestriction, int userId) {
8916        switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
8917            case UserManager.RESTRICTION_NOT_SET:
8918                return false;
8919            case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
8920                return !isDeviceOwner(admin, userId);
8921            case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
8922                return !isProfileOwner(admin, userId);
8923            default:
8924                return true;
8925        }
8926    }
8927
8928    @Override
8929    public boolean switchUser(ComponentName who, UserHandle userHandle) {
8930        Preconditions.checkNotNull(who, "ComponentName is null");
8931
8932        synchronized (this) {
8933            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8934
8935            long id = mInjector.binderClearCallingIdentity();
8936            try {
8937                int userId = UserHandle.USER_SYSTEM;
8938                if (userHandle != null) {
8939                    userId = userHandle.getIdentifier();
8940                }
8941                return mInjector.getIActivityManager().switchUser(userId);
8942            } catch (RemoteException e) {
8943                Log.e(LOG_TAG, "Couldn't switch user", e);
8944                return false;
8945            } finally {
8946                mInjector.binderRestoreCallingIdentity(id);
8947            }
8948        }
8949    }
8950
8951    @Override
8952    public boolean startUserInBackground(ComponentName who, UserHandle userHandle) {
8953        Preconditions.checkNotNull(who, "ComponentName is null");
8954        Preconditions.checkNotNull(userHandle, "UserHandle is null");
8955
8956        synchronized (this) {
8957            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8958        }
8959
8960        final int userId = userHandle.getIdentifier();
8961        if (isManagedProfile(userId)) {
8962            Log.w(LOG_TAG, "Managed profile cannot be started in background");
8963            return false;
8964        }
8965
8966        final long id = mInjector.binderClearCallingIdentity();
8967        try {
8968            if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) {
8969                Log.w(LOG_TAG, "Cannot start more users in background");
8970                return false;
8971            }
8972
8973            return mInjector.getIActivityManager().startUserInBackground(userId);
8974        } catch (RemoteException e) {
8975            // Same process, should not happen.
8976            return false;
8977        } finally {
8978            mInjector.binderRestoreCallingIdentity(id);
8979        }
8980    }
8981
8982    @Override
8983    public boolean stopUser(ComponentName who, UserHandle userHandle) {
8984        Preconditions.checkNotNull(who, "ComponentName is null");
8985        Preconditions.checkNotNull(userHandle, "UserHandle is null");
8986
8987        synchronized (this) {
8988            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8989        }
8990
8991        final int userId = userHandle.getIdentifier();
8992        if (isManagedProfile(userId)) {
8993            Log.w(LOG_TAG, "Managed profile cannot be stopped");
8994            return false;
8995        }
8996
8997        final long id = mInjector.binderClearCallingIdentity();
8998        try {
8999            return mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)
9000                    == USER_OP_SUCCESS;
9001        } catch (RemoteException e) {
9002            // Same process, should not happen.
9003            return false;
9004        } finally {
9005            mInjector.binderRestoreCallingIdentity(id);
9006        }
9007    }
9008
9009    @Override
9010    public boolean logoutUser(ComponentName who) {
9011        Preconditions.checkNotNull(who, "ComponentName is null");
9012
9013        final int callingUserId = mInjector.userHandleGetCallingUserId();
9014        synchronized (this) {
9015            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9016            if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
9017                throw new SecurityException("Admin " + who +
9018                        " is neither the device owner or affiliated user's profile owner.");
9019            }
9020        }
9021
9022        if (isManagedProfile(callingUserId)) {
9023            Log.w(LOG_TAG, "Managed profile cannot be logout");
9024            return false;
9025        }
9026
9027        final long id = mInjector.binderClearCallingIdentity();
9028        try {
9029            if (!mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM)) {
9030                Log.w(LOG_TAG, "Failed to switch to primary user");
9031                return false;
9032            }
9033            return mInjector.getIActivityManager().stopUser(callingUserId, true /*force*/, null)
9034                    == USER_OP_SUCCESS;
9035        } catch (RemoteException e) {
9036            // Same process, should not happen.
9037            return false;
9038        } finally {
9039            mInjector.binderRestoreCallingIdentity(id);
9040        }
9041    }
9042
9043    @Override
9044    public List<UserHandle> getSecondaryUsers(ComponentName who) {
9045        Preconditions.checkNotNull(who, "ComponentName is null");
9046        synchronized (this) {
9047            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9048        }
9049
9050        final long id = mInjector.binderClearCallingIdentity();
9051        try {
9052            final List<UserInfo> userInfos = mInjector.getUserManager().getUsers(true
9053                    /*excludeDying*/);
9054            final List<UserHandle> userHandles = new ArrayList<>();
9055            for (UserInfo userInfo : userInfos) {
9056                UserHandle userHandle = userInfo.getUserHandle();
9057                if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) {
9058                    userHandles.add(userInfo.getUserHandle());
9059                }
9060            }
9061            return userHandles;
9062        } finally {
9063            mInjector.binderRestoreCallingIdentity(id);
9064        }
9065    }
9066
9067    @Override
9068    public boolean isEphemeralUser(ComponentName who) {
9069        Preconditions.checkNotNull(who, "ComponentName is null");
9070        synchronized (this) {
9071            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9072        }
9073
9074        final int callingUserId = mInjector.userHandleGetCallingUserId();
9075        final long id = mInjector.binderClearCallingIdentity();
9076        try {
9077            return mInjector.getUserManager().isUserEphemeral(callingUserId);
9078        } finally {
9079            mInjector.binderRestoreCallingIdentity(id);
9080        }
9081    }
9082
9083    @Override
9084    public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
9085            String packageName) {
9086        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9087                DELEGATION_APP_RESTRICTIONS);
9088
9089        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
9090        final long id = mInjector.binderClearCallingIdentity();
9091        try {
9092           Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
9093           // if no restrictions were saved, mUserManager.getApplicationRestrictions
9094           // returns null, but DPM method should return an empty Bundle as per JavaDoc
9095           return bundle != null ? bundle : Bundle.EMPTY;
9096        } finally {
9097            mInjector.binderRestoreCallingIdentity(id);
9098        }
9099    }
9100
9101    @Override
9102    public String[] setPackagesSuspended(ComponentName who, String callerPackage,
9103            String[] packageNames, boolean suspended) {
9104        int callingUserId = UserHandle.getCallingUserId();
9105        synchronized (this) {
9106            // Ensure the caller is a DO/PO or a package access delegate.
9107            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9108                    DELEGATION_PACKAGE_ACCESS);
9109
9110            long id = mInjector.binderClearCallingIdentity();
9111            try {
9112                return mIPackageManager.setPackagesSuspendedAsUser(
9113                        packageNames, suspended, callingUserId);
9114            } catch (RemoteException re) {
9115                // Shouldn't happen.
9116                Slog.e(LOG_TAG, "Failed talking to the package manager", re);
9117            } finally {
9118                mInjector.binderRestoreCallingIdentity(id);
9119            }
9120            return packageNames;
9121        }
9122    }
9123
9124    @Override
9125    public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
9126        int callingUserId = UserHandle.getCallingUserId();
9127        synchronized (this) {
9128            // Ensure the caller is a DO/PO or a package access delegate.
9129            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9130                    DELEGATION_PACKAGE_ACCESS);
9131
9132            long id = mInjector.binderClearCallingIdentity();
9133            try {
9134                return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
9135            } catch (RemoteException re) {
9136                // Shouldn't happen.
9137                Slog.e(LOG_TAG, "Failed talking to the package manager", re);
9138            } finally {
9139                mInjector.binderRestoreCallingIdentity(id);
9140            }
9141            return false;
9142        }
9143    }
9144
9145    @Override
9146    public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
9147        Preconditions.checkNotNull(who, "ComponentName is null");
9148        if (!UserRestrictionsUtils.isValidRestriction(key)) {
9149            return;
9150        }
9151
9152        final int userHandle = mInjector.userHandleGetCallingUserId();
9153        synchronized (this) {
9154            final ActiveAdmin activeAdmin =
9155                    getActiveAdminForCallerLocked(who,
9156                            DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9157            final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
9158            if (isDeviceOwner) {
9159                if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
9160                    throw new SecurityException("Device owner cannot set user restriction " + key);
9161                }
9162            } else { // profile owner
9163                if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
9164                    throw new SecurityException("Profile owner cannot set user restriction " + key);
9165                }
9166            }
9167
9168            // Save the restriction to ActiveAdmin.
9169            final Bundle restrictions = activeAdmin.ensureUserRestrictions();
9170            if (enabledFromThisOwner) {
9171                restrictions.putBoolean(key, true);
9172            } else {
9173                restrictions.remove(key);
9174            }
9175            saveUserRestrictionsLocked(userHandle);
9176        }
9177    }
9178
9179    private void saveUserRestrictionsLocked(int userId) {
9180        saveSettingsLocked(userId);
9181        pushUserRestrictions(userId);
9182        sendChangedNotification(userId);
9183    }
9184
9185    private void pushUserRestrictions(int userId) {
9186        synchronized (this) {
9187            final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId);
9188            final Bundle userRestrictions;
9189            // Whether device owner enforces camera restriction.
9190            boolean disallowCameraGlobally = false;
9191
9192            if (isDeviceOwner) {
9193                final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9194                if (deviceOwner == null) {
9195                    return; // Shouldn't happen.
9196                }
9197                userRestrictions = deviceOwner.userRestrictions;
9198                // DO can disable camera globally.
9199                disallowCameraGlobally = deviceOwner.disableCamera;
9200            } else {
9201                final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
9202                userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null;
9203            }
9204
9205            // Whether any admin enforces camera restriction.
9206            final int cameraRestrictionScope =
9207                    getCameraRestrictionScopeLocked(userId, disallowCameraGlobally);
9208
9209            mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions,
9210                    isDeviceOwner, cameraRestrictionScope);
9211        }
9212    }
9213
9214    /**
9215     * Get the scope of camera restriction for a given user if any.
9216     */
9217    private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) {
9218        if (disallowCameraGlobally) {
9219            return UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
9220        } else if (getCameraDisabled(
9221                /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) {
9222            return UserManagerInternal.CAMERA_DISABLED_LOCALLY;
9223        }
9224        return UserManagerInternal.CAMERA_NOT_DISABLED;
9225    }
9226
9227    @Override
9228    public Bundle getUserRestrictions(ComponentName who) {
9229        if (!mHasFeature) {
9230            return null;
9231        }
9232        Preconditions.checkNotNull(who, "ComponentName is null");
9233        synchronized (this) {
9234            final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
9235                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9236            return activeAdmin.userRestrictions;
9237        }
9238    }
9239
9240    @Override
9241    public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
9242            boolean hidden) {
9243        int callingUserId = UserHandle.getCallingUserId();
9244        synchronized (this) {
9245            // Ensure the caller is a DO/PO or a package access delegate.
9246            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9247                    DELEGATION_PACKAGE_ACCESS);
9248
9249            long id = mInjector.binderClearCallingIdentity();
9250            try {
9251                return mIPackageManager.setApplicationHiddenSettingAsUser(
9252                        packageName, hidden, callingUserId);
9253            } catch (RemoteException re) {
9254                // shouldn't happen
9255                Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
9256            } finally {
9257                mInjector.binderRestoreCallingIdentity(id);
9258            }
9259            return false;
9260        }
9261    }
9262
9263    @Override
9264    public boolean isApplicationHidden(ComponentName who, String callerPackage,
9265            String packageName) {
9266        int callingUserId = UserHandle.getCallingUserId();
9267        synchronized (this) {
9268            // Ensure the caller is a DO/PO or a package access delegate.
9269            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9270                    DELEGATION_PACKAGE_ACCESS);
9271
9272            long id = mInjector.binderClearCallingIdentity();
9273            try {
9274                return mIPackageManager.getApplicationHiddenSettingAsUser(
9275                        packageName, callingUserId);
9276            } catch (RemoteException re) {
9277                // shouldn't happen
9278                Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
9279            } finally {
9280                mInjector.binderRestoreCallingIdentity(id);
9281            }
9282            return false;
9283        }
9284    }
9285
9286    @Override
9287    public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
9288        synchronized (this) {
9289            // Ensure the caller is a DO/PO or an enable system app delegate.
9290            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9291                    DELEGATION_ENABLE_SYSTEM_APP);
9292
9293            final boolean isDemo = isCurrentUserDemo();
9294
9295            int userId = UserHandle.getCallingUserId();
9296            long id = mInjector.binderClearCallingIdentity();
9297
9298            try {
9299                if (VERBOSE_LOG) {
9300                    Slog.v(LOG_TAG, "installing " + packageName + " for "
9301                            + userId);
9302                }
9303
9304                int parentUserId = getProfileParentId(userId);
9305                if (!isDemo && !isSystemApp(mIPackageManager, packageName, parentUserId)) {
9306                    throw new IllegalArgumentException("Only system apps can be enabled this way.");
9307                }
9308
9309                // Install the app.
9310                mIPackageManager.installExistingPackageAsUser(packageName, userId,
9311                        0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
9312                if (isDemo) {
9313                    // Ensure the app is also ENABLED for demo users.
9314                    mIPackageManager.setApplicationEnabledSetting(packageName,
9315                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
9316                            PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
9317                }
9318            } catch (RemoteException re) {
9319                // shouldn't happen
9320                Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
9321            } finally {
9322                mInjector.binderRestoreCallingIdentity(id);
9323            }
9324        }
9325    }
9326
9327    @Override
9328    public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
9329        synchronized (this) {
9330            // Ensure the caller is a DO/PO or an enable system app delegate.
9331            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9332                    DELEGATION_ENABLE_SYSTEM_APP);
9333
9334            int userId = UserHandle.getCallingUserId();
9335            long id = mInjector.binderClearCallingIdentity();
9336
9337            try {
9338                int parentUserId = getProfileParentId(userId);
9339                List<ResolveInfo> activitiesToEnable = mIPackageManager
9340                        .queryIntentActivities(intent,
9341                                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
9342                                PackageManager.MATCH_DIRECT_BOOT_AWARE
9343                                        | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
9344                                parentUserId)
9345                        .getList();
9346
9347                if (VERBOSE_LOG) {
9348                    Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
9349                }
9350                int numberOfAppsInstalled = 0;
9351                if (activitiesToEnable != null) {
9352                    for (ResolveInfo info : activitiesToEnable) {
9353                        if (info.activityInfo != null) {
9354                            String packageName = info.activityInfo.packageName;
9355                            if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
9356                                numberOfAppsInstalled++;
9357                                mIPackageManager.installExistingPackageAsUser(packageName, userId,
9358                                        0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
9359                            } else {
9360                                Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
9361                                        + " system app");
9362                            }
9363                        }
9364                    }
9365                }
9366                return numberOfAppsInstalled;
9367            } catch (RemoteException e) {
9368                // shouldn't happen
9369                Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
9370                return 0;
9371            } finally {
9372                mInjector.binderRestoreCallingIdentity(id);
9373            }
9374        }
9375    }
9376
9377    private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
9378            throws RemoteException {
9379        ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
9380                userId);
9381        if (appInfo == null) {
9382            throw new IllegalArgumentException("The application " + packageName +
9383                    " is not present on this device");
9384        }
9385        return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9386    }
9387
9388    @Override
9389    public boolean installExistingPackage(ComponentName who, String callerPackage,
9390            String packageName) {
9391        synchronized (this) {
9392            // Ensure the caller is a PO or an install existing package delegate
9393            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9394                    DELEGATION_INSTALL_EXISTING_PACKAGE);
9395            final int callingUserId = mInjector.userHandleGetCallingUserId();
9396            if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
9397                throw new SecurityException("Admin " + who +
9398                        " is neither the device owner or affiliated user's profile owner.");
9399            }
9400
9401            final long id = mInjector.binderClearCallingIdentity();
9402            try {
9403                if (VERBOSE_LOG) {
9404                    Slog.v(LOG_TAG, "installing " + packageName + " for "
9405                            + callingUserId);
9406                }
9407
9408                // Install the package.
9409                return mIPackageManager.installExistingPackageAsUser(packageName, callingUserId,
9410                        0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY)
9411                        == PackageManager.INSTALL_SUCCEEDED;
9412            } catch (RemoteException re) {
9413                // shouldn't happen
9414                return false;
9415            } finally {
9416                mInjector.binderRestoreCallingIdentity(id);
9417            }
9418        }
9419    }
9420
9421    @Override
9422    public void setAccountManagementDisabled(ComponentName who, String accountType,
9423            boolean disabled) {
9424        if (!mHasFeature) {
9425            return;
9426        }
9427        Preconditions.checkNotNull(who, "ComponentName is null");
9428        synchronized (this) {
9429            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
9430                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9431            if (disabled) {
9432                ap.accountTypesWithManagementDisabled.add(accountType);
9433            } else {
9434                ap.accountTypesWithManagementDisabled.remove(accountType);
9435            }
9436            saveSettingsLocked(UserHandle.getCallingUserId());
9437        }
9438    }
9439
9440    @Override
9441    public String[] getAccountTypesWithManagementDisabled() {
9442        return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
9443    }
9444
9445    @Override
9446    public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
9447        enforceFullCrossUsersPermission(userId);
9448        if (!mHasFeature) {
9449            return null;
9450        }
9451        synchronized (this) {
9452            DevicePolicyData policy = getUserData(userId);
9453            final int N = policy.mAdminList.size();
9454            ArraySet<String> resultSet = new ArraySet<>();
9455            for (int i = 0; i < N; i++) {
9456                ActiveAdmin admin = policy.mAdminList.get(i);
9457                resultSet.addAll(admin.accountTypesWithManagementDisabled);
9458            }
9459            return resultSet.toArray(new String[resultSet.size()]);
9460        }
9461    }
9462
9463    @Override
9464    public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
9465            boolean uninstallBlocked) {
9466        final int userId = UserHandle.getCallingUserId();
9467        synchronized (this) {
9468            // Ensure the caller is a DO/PO or a block uninstall delegate
9469            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9470                    DELEGATION_BLOCK_UNINSTALL);
9471
9472            long id = mInjector.binderClearCallingIdentity();
9473            try {
9474                mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
9475            } catch (RemoteException re) {
9476                // Shouldn't happen.
9477                Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
9478            } finally {
9479                mInjector.binderRestoreCallingIdentity(id);
9480            }
9481        }
9482    }
9483
9484    @Override
9485    public boolean isUninstallBlocked(ComponentName who, String packageName) {
9486        // This function should return true if and only if the package is blocked by
9487        // setUninstallBlocked(). It should still return false for other cases of blocks, such as
9488        // when the package is a system app, or when it is an active device admin.
9489        final int userId = UserHandle.getCallingUserId();
9490
9491        synchronized (this) {
9492            if (who != null) {
9493                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9494            }
9495
9496            long id = mInjector.binderClearCallingIdentity();
9497            try {
9498                return mIPackageManager.getBlockUninstallForUser(packageName, userId);
9499            } catch (RemoteException re) {
9500                // Shouldn't happen.
9501                Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
9502            } finally {
9503                mInjector.binderRestoreCallingIdentity(id);
9504            }
9505        }
9506        return false;
9507    }
9508
9509    @Override
9510    public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
9511        if (!mHasFeature) {
9512            return;
9513        }
9514        Preconditions.checkNotNull(who, "ComponentName is null");
9515        synchronized (this) {
9516            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9517                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9518            if (admin.disableCallerId != disabled) {
9519                admin.disableCallerId = disabled;
9520                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
9521            }
9522        }
9523    }
9524
9525    @Override
9526    public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
9527        if (!mHasFeature) {
9528            return false;
9529        }
9530        Preconditions.checkNotNull(who, "ComponentName is null");
9531        synchronized (this) {
9532            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9533                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9534            return admin.disableCallerId;
9535        }
9536    }
9537
9538    @Override
9539    public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
9540        enforceCrossUsersPermission(userId);
9541        synchronized (this) {
9542            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9543            return (admin != null) ? admin.disableCallerId : false;
9544        }
9545    }
9546
9547    @Override
9548    public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
9549        if (!mHasFeature) {
9550            return;
9551        }
9552        Preconditions.checkNotNull(who, "ComponentName is null");
9553        synchronized (this) {
9554            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9555                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9556            if (admin.disableContactsSearch != disabled) {
9557                admin.disableContactsSearch = disabled;
9558                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
9559            }
9560        }
9561    }
9562
9563    @Override
9564    public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
9565        if (!mHasFeature) {
9566            return false;
9567        }
9568        Preconditions.checkNotNull(who, "ComponentName is null");
9569        synchronized (this) {
9570            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9571                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9572            return admin.disableContactsSearch;
9573        }
9574    }
9575
9576    @Override
9577    public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
9578        enforceCrossUsersPermission(userId);
9579        synchronized (this) {
9580            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9581            return (admin != null) ? admin.disableContactsSearch : false;
9582        }
9583    }
9584
9585    @Override
9586    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
9587            boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
9588        final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
9589                actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
9590        final int callingUserId = UserHandle.getCallingUserId();
9591
9592        final long ident = mInjector.binderClearCallingIdentity();
9593        try {
9594            synchronized (this) {
9595                final int managedUserId = getManagedUserId(callingUserId);
9596                if (managedUserId < 0) {
9597                    return;
9598                }
9599                if (isCrossProfileQuickContactDisabled(managedUserId)) {
9600                    if (VERBOSE_LOG) {
9601                        Log.v(LOG_TAG,
9602                                "Cross-profile contacts access disabled for user " + managedUserId);
9603                    }
9604                    return;
9605                }
9606                ContactsInternal.startQuickContactWithErrorToastForUser(
9607                        mContext, intent, new UserHandle(managedUserId));
9608            }
9609        } finally {
9610            mInjector.binderRestoreCallingIdentity(ident);
9611        }
9612    }
9613
9614    /**
9615     * @return true if cross-profile QuickContact is disabled
9616     */
9617    private boolean isCrossProfileQuickContactDisabled(int userId) {
9618        return getCrossProfileCallerIdDisabledForUser(userId)
9619                && getCrossProfileContactsSearchDisabledForUser(userId);
9620    }
9621
9622    /**
9623     * @return the user ID of the managed user that is linked to the current user, if any.
9624     * Otherwise -1.
9625     */
9626    public int getManagedUserId(int callingUserId) {
9627        if (VERBOSE_LOG) {
9628            Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
9629        }
9630
9631        for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
9632            if (ui.id == callingUserId || !ui.isManagedProfile()) {
9633                continue; // Caller user self, or not a managed profile.  Skip.
9634            }
9635            if (VERBOSE_LOG) {
9636                Log.v(LOG_TAG, "Managed user=" + ui.id);
9637            }
9638            return ui.id;
9639        }
9640        if (VERBOSE_LOG) {
9641            Log.v(LOG_TAG, "Managed user not found.");
9642        }
9643        return -1;
9644    }
9645
9646    @Override
9647    public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
9648        if (!mHasFeature) {
9649            return;
9650        }
9651        Preconditions.checkNotNull(who, "ComponentName is null");
9652        synchronized (this) {
9653            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9654                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9655            if (admin.disableBluetoothContactSharing != disabled) {
9656                admin.disableBluetoothContactSharing = disabled;
9657                saveSettingsLocked(UserHandle.getCallingUserId());
9658            }
9659        }
9660    }
9661
9662    @Override
9663    public boolean getBluetoothContactSharingDisabled(ComponentName who) {
9664        if (!mHasFeature) {
9665            return false;
9666        }
9667        Preconditions.checkNotNull(who, "ComponentName is null");
9668        synchronized (this) {
9669            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9670                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9671            return admin.disableBluetoothContactSharing;
9672        }
9673    }
9674
9675    @Override
9676    public boolean getBluetoothContactSharingDisabledForUser(int userId) {
9677        // TODO: Should there be a check to make sure this relationship is
9678        // within a profile group?
9679        // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
9680        synchronized (this) {
9681            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9682            return (admin != null) ? admin.disableBluetoothContactSharing : false;
9683        }
9684    }
9685
9686    @Override
9687    public void setLockTaskPackages(ComponentName who, String[] packages)
9688            throws SecurityException {
9689        Preconditions.checkNotNull(who, "ComponentName is null");
9690        Preconditions.checkNotNull(packages, "packages is null");
9691
9692        synchronized (this) {
9693            enforceCanCallLockTaskLocked(who);
9694            final int userHandle = mInjector.userHandleGetCallingUserId();
9695            setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
9696        }
9697    }
9698
9699    private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
9700        DevicePolicyData policy = getUserData(userHandle);
9701        policy.mLockTaskPackages = packages;
9702
9703        // Store the settings persistently.
9704        saveSettingsLocked(userHandle);
9705        updateLockTaskPackagesLocked(packages, userHandle);
9706    }
9707
9708    @Override
9709    public String[] getLockTaskPackages(ComponentName who) {
9710        Preconditions.checkNotNull(who, "ComponentName is null");
9711
9712        final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
9713        synchronized (this) {
9714            enforceCanCallLockTaskLocked(who);
9715            final List<String> packages = getUserData(userHandle).mLockTaskPackages;
9716            return packages.toArray(new String[packages.size()]);
9717        }
9718    }
9719
9720    @Override
9721    public boolean isLockTaskPermitted(String pkg) {
9722        final int userHandle = mInjector.userHandleGetCallingUserId();
9723        synchronized (this) {
9724            return getUserData(userHandle).mLockTaskPackages.contains(pkg);
9725        }
9726    }
9727
9728    @Override
9729    public void setLockTaskFeatures(ComponentName who, int flags) {
9730        Preconditions.checkNotNull(who, "ComponentName is null");
9731        final int userHandle = mInjector.userHandleGetCallingUserId();
9732        synchronized (this) {
9733            enforceCanCallLockTaskLocked(who);
9734            setLockTaskFeaturesLocked(userHandle, flags);
9735        }
9736    }
9737
9738    private void setLockTaskFeaturesLocked(int userHandle, int flags) {
9739        DevicePolicyData policy = getUserData(userHandle);
9740        policy.mLockTaskFeatures = flags;
9741        saveSettingsLocked(userHandle);
9742        updateLockTaskFeaturesLocked(flags, userHandle);
9743    }
9744
9745    @Override
9746    public int getLockTaskFeatures(ComponentName who) {
9747        Preconditions.checkNotNull(who, "ComponentName is null");
9748        final int userHandle = mInjector.userHandleGetCallingUserId();
9749        synchronized (this) {
9750            enforceCanCallLockTaskLocked(who);
9751            return getUserData(userHandle).mLockTaskFeatures;
9752        }
9753    }
9754
9755    private void maybeClearLockTaskPolicyLocked() {
9756        final long ident = mInjector.binderClearCallingIdentity();
9757        try {
9758            final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
9759            for (int i = userInfos.size() - 1; i >= 0; i--) {
9760                int userId = userInfos.get(i).id;
9761                if (canUserUseLockTaskLocked(userId)) {
9762                    continue;
9763                }
9764
9765                final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
9766                if (!lockTaskPackages.isEmpty()) {
9767                    Slog.d(LOG_TAG,
9768                            "User id " + userId + " not affiliated. Clearing lock task packages");
9769                    setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
9770                }
9771                final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures;
9772                if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){
9773                    Slog.d(LOG_TAG,
9774                            "User id " + userId + " not affiliated. Clearing lock task features");
9775                    setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
9776                }
9777            }
9778        } finally {
9779            mInjector.binderRestoreCallingIdentity(ident);
9780        }
9781    }
9782
9783    @Override
9784    public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
9785        if (!isCallerWithSystemUid()) {
9786            throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
9787        }
9788        synchronized (this) {
9789            final DevicePolicyData policy = getUserData(userHandle);
9790
9791            if (policy.mStatusBarDisabled) {
9792                // Status bar is managed by LockTaskController during LockTask, so we cancel this
9793                // policy when LockTask starts, and reapply it when LockTask ends
9794                setStatusBarDisabledInternal(!isEnabled, userHandle);
9795            }
9796
9797            Bundle adminExtras = new Bundle();
9798            adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
9799            for (ActiveAdmin admin : policy.mAdminList) {
9800                final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
9801                final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
9802                if (ownsDevice || ownsProfile) {
9803                    if (isEnabled) {
9804                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
9805                                adminExtras, null);
9806                    } else {
9807                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
9808                    }
9809                }
9810            }
9811        }
9812    }
9813
9814    @Override
9815    public void setGlobalSetting(ComponentName who, String setting, String value) {
9816        Preconditions.checkNotNull(who, "ComponentName is null");
9817
9818        synchronized (this) {
9819            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9820
9821            // Some settings are no supported any more. However we do not want to throw a
9822            // SecurityException to avoid breaking apps.
9823            if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
9824                Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
9825                return;
9826            }
9827
9828            if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)
9829                    && !UserManager.isDeviceInDemoMode(mContext)) {
9830                throw new SecurityException(String.format(
9831                        "Permission denial: device owners cannot update %1$s", setting));
9832            }
9833
9834            if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
9835                // ignore if it contradicts an existing policy
9836                long timeMs = getMaximumTimeToLock(
9837                        who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
9838                if (timeMs > 0 && timeMs < Long.MAX_VALUE) {
9839                    return;
9840                }
9841            }
9842
9843            long id = mInjector.binderClearCallingIdentity();
9844            try {
9845                mInjector.settingsGlobalPutString(setting, value);
9846            } finally {
9847                mInjector.binderRestoreCallingIdentity(id);
9848            }
9849        }
9850    }
9851
9852    @Override
9853    public void setSystemSetting(ComponentName who, String setting, String value) {
9854        Preconditions.checkNotNull(who, "ComponentName is null");
9855        Preconditions.checkStringNotEmpty(setting, "String setting is null or empty");
9856
9857        synchronized (this) {
9858            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9859
9860            if (!SYSTEM_SETTINGS_WHITELIST.contains(setting)) {
9861                throw new SecurityException(String.format(
9862                        "Permission denial: device owners cannot update %1$s", setting));
9863            }
9864
9865            mInjector.binderWithCleanCallingIdentity(() -> mInjector.settingsSystemPutString(
9866                    setting, value));
9867        }
9868    }
9869
9870    @Override
9871    public boolean setTime(ComponentName who, long millis) {
9872        Preconditions.checkNotNull(who, "ComponentName is null in setTime");
9873        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9874        // Don't allow set time when auto time is on.
9875        if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) {
9876            return false;
9877        }
9878        mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis));
9879        return true;
9880    }
9881
9882    @Override
9883    public boolean setTimeZone(ComponentName who, String timeZone) {
9884        Preconditions.checkNotNull(who, "ComponentName is null in setTimeZone");
9885        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9886        // Don't allow set timezone when auto timezone is on.
9887        if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) {
9888            return false;
9889        }
9890        mInjector.binderWithCleanCallingIdentity(() ->
9891            mInjector.getAlarmManager().setTimeZone(timeZone));
9892        return true;
9893    }
9894
9895    @Override
9896    public void setSecureSetting(ComponentName who, String setting, String value) {
9897        Preconditions.checkNotNull(who, "ComponentName is null");
9898        int callingUserId = mInjector.userHandleGetCallingUserId();
9899
9900        synchronized (this) {
9901            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9902
9903            if (isDeviceOwner(who, callingUserId)) {
9904                if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)
9905                        && !isCurrentUserDemo()) {
9906                    throw new SecurityException(String.format(
9907                            "Permission denial: Device owners cannot update %1$s", setting));
9908                }
9909            } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) {
9910                throw new SecurityException(String.format(
9911                        "Permission denial: Profile owners cannot update %1$s", setting));
9912            }
9913            if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
9914                if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
9915                    throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
9916                            + " is deprecated. Please use the user restriction "
9917                            + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " instead.");
9918                }
9919                if (!mUserManager.isManagedProfile(callingUserId)) {
9920                    Slog.e(LOG_TAG, "Ignoring setSecureSetting request for "
9921                            + setting + ". User restriction "
9922                            + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES
9923                            + " should be used instead.");
9924                } else {
9925                    try {
9926                        setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
9927                                (Integer.parseInt(value) == 0) ? true : false);
9928                    } catch (NumberFormatException exc) {
9929                        Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
9930                    }
9931                }
9932                return;
9933            }
9934            long id = mInjector.binderClearCallingIdentity();
9935            try {
9936                if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
9937                    final String currentValue = mInjector.settingsSecureGetStringForUser(
9938                            Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
9939                    if (!TextUtils.equals(currentValue, value)) {
9940                        // Tell the content observer that the next change will be due to the owner
9941                        // changing the value. There is a small race condition here that we cannot
9942                        // avoid: Change notifications are sent asynchronously, so it is possible
9943                        // that there are prior notifications queued up before the one we are about
9944                        // to trigger. This is a corner case that will have no impact in practice.
9945                        mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
9946                    }
9947                    getUserData(callingUserId).mCurrentInputMethodSet = true;
9948                    saveSettingsLocked(callingUserId);
9949                }
9950                mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
9951            } finally {
9952                mInjector.binderRestoreCallingIdentity(id);
9953            }
9954        }
9955    }
9956
9957    @Override
9958    public void setMasterVolumeMuted(ComponentName who, boolean on) {
9959        Preconditions.checkNotNull(who, "ComponentName is null");
9960        synchronized (this) {
9961            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9962            setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on);
9963        }
9964    }
9965
9966    @Override
9967    public boolean isMasterVolumeMuted(ComponentName who) {
9968        Preconditions.checkNotNull(who, "ComponentName is null");
9969        synchronized (this) {
9970            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9971
9972            AudioManager audioManager =
9973                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
9974            return audioManager.isMasterMute();
9975        }
9976    }
9977
9978    @Override
9979    public void setUserIcon(ComponentName who, Bitmap icon) {
9980        synchronized (this) {
9981            Preconditions.checkNotNull(who, "ComponentName is null");
9982            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9983
9984            int userId = UserHandle.getCallingUserId();
9985            long id = mInjector.binderClearCallingIdentity();
9986            try {
9987                mUserManagerInternal.setUserIcon(userId, icon);
9988            } finally {
9989                mInjector.binderRestoreCallingIdentity(id);
9990            }
9991        }
9992    }
9993
9994    @Override
9995    public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
9996        Preconditions.checkNotNull(who, "ComponentName is null");
9997        final int userId = mInjector.userHandleGetCallingUserId();
9998        synchronized (this) {
9999            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10000            if (!isUserAffiliatedWithDeviceLocked(userId)) {
10001                throw new SecurityException("Admin " + who +
10002                        " is neither the device owner or affiliated user's profile owner.");
10003            }
10004        }
10005        if (isManagedProfile(userId)) {
10006            throw new SecurityException("Managed profile cannot disable keyguard");
10007        }
10008
10009        long ident = mInjector.binderClearCallingIdentity();
10010        try {
10011            // disallow disabling the keyguard if a password is currently set
10012            if (disabled && mLockPatternUtils.isSecure(userId)) {
10013                return false;
10014            }
10015            mLockPatternUtils.setLockScreenDisabled(disabled, userId);
10016            mInjector.getIWindowManager().dismissKeyguard(null /* callback */, null /* message */);
10017        } catch (RemoteException e) {
10018            // Same process, does not happen.
10019        } finally {
10020            mInjector.binderRestoreCallingIdentity(ident);
10021        }
10022        return true;
10023    }
10024
10025    @Override
10026    public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
10027        int userId = UserHandle.getCallingUserId();
10028        synchronized (this) {
10029            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10030            if (!isUserAffiliatedWithDeviceLocked(userId)) {
10031                throw new SecurityException("Admin " + who +
10032                        " is neither the device owner or affiliated user's profile owner.");
10033            }
10034            if (isManagedProfile(userId)) {
10035                throw new SecurityException("Managed profile cannot disable status bar");
10036            }
10037            DevicePolicyData policy = getUserData(userId);
10038            if (policy.mStatusBarDisabled != disabled) {
10039                boolean isLockTaskMode = false;
10040                try {
10041                    isLockTaskMode = mInjector.getIActivityManager().getLockTaskModeState()
10042                            != LOCK_TASK_MODE_NONE;
10043                } catch (RemoteException e) {
10044                    Slog.e(LOG_TAG, "Failed to get LockTask mode");
10045                }
10046                if (!isLockTaskMode) {
10047                    if (!setStatusBarDisabledInternal(disabled, userId)) {
10048                        return false;
10049                    }
10050                }
10051                policy.mStatusBarDisabled = disabled;
10052                saveSettingsLocked(userId);
10053            }
10054        }
10055        return true;
10056    }
10057
10058    private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
10059        long ident = mInjector.binderClearCallingIdentity();
10060        try {
10061            IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
10062                    ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
10063            if (statusBarService != null) {
10064                int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
10065                int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
10066                statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
10067                statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
10068                return true;
10069            }
10070        } catch (RemoteException e) {
10071            Slog.e(LOG_TAG, "Failed to disable the status bar", e);
10072        } finally {
10073            mInjector.binderRestoreCallingIdentity(ident);
10074        }
10075        return false;
10076    }
10077
10078    /**
10079     * We need to update the internal state of whether a user has completed setup or a
10080     * device has paired once. After that, we ignore any changes that reset the
10081     * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
10082     * as we don't trust any apps that might try to reset them.
10083     * <p>
10084     * Unfortunately, we don't know which user's setup state was changed, so we write all of
10085     * them.
10086     */
10087    void updateUserSetupCompleteAndPaired() {
10088        List<UserInfo> users = mUserManager.getUsers(true);
10089        final int N = users.size();
10090        for (int i = 0; i < N; i++) {
10091            int userHandle = users.get(i).id;
10092            if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
10093                    userHandle) != 0) {
10094                DevicePolicyData policy = getUserData(userHandle);
10095                if (!policy.mUserSetupComplete) {
10096                    policy.mUserSetupComplete = true;
10097                    synchronized (this) {
10098                        saveSettingsLocked(userHandle);
10099                    }
10100                }
10101            }
10102            if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
10103                    userHandle) != 0) {
10104                DevicePolicyData policy = getUserData(userHandle);
10105                if (!policy.mPaired) {
10106                    policy.mPaired = true;
10107                    synchronized (this) {
10108                        saveSettingsLocked(userHandle);
10109                    }
10110                }
10111            }
10112        }
10113    }
10114
10115    private class SetupContentObserver extends ContentObserver {
10116        private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
10117                Settings.Secure.USER_SETUP_COMPLETE);
10118        private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
10119                Settings.Global.DEVICE_PROVISIONED);
10120        private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
10121        private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
10122                Settings.Secure.DEFAULT_INPUT_METHOD);
10123
10124        @GuardedBy("DevicePolicyManagerService.this")
10125        private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();
10126
10127        public SetupContentObserver(Handler handler) {
10128            super(handler);
10129        }
10130
10131        void register() {
10132            mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
10133            mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
10134            if (mIsWatch) {
10135                mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
10136            }
10137            mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
10138        }
10139
10140        private void addPendingChangeByOwnerLocked(int userId) {
10141            mUserIdsWithPendingChangesByOwner.add(userId);
10142        }
10143
10144        @Override
10145        public void onChange(boolean selfChange, Uri uri, int userId) {
10146            if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
10147                updateUserSetupCompleteAndPaired();
10148            } else if (mDeviceProvisioned.equals(uri)) {
10149                synchronized (DevicePolicyManagerService.this) {
10150                    // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
10151                    // is delayed until device is marked as provisioned.
10152                    setDeviceOwnerSystemPropertyLocked();
10153                }
10154            } else if (mDefaultImeChanged.equals(uri)) {
10155                synchronized (DevicePolicyManagerService.this) {
10156                    if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
10157                        // This change notification was triggered by the owner changing the current
10158                        // IME. Ignore it.
10159                        mUserIdsWithPendingChangesByOwner.remove(userId);
10160                    } else {
10161                        // This change notification was triggered by the user manually changing the
10162                        // current IME.
10163                        getUserData(userId).mCurrentInputMethodSet = false;
10164                        saveSettingsLocked(userId);
10165                    }
10166                }
10167            }
10168        }
10169    }
10170
10171    @VisibleForTesting
10172    final class LocalService extends DevicePolicyManagerInternal {
10173        private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
10174
10175        @Override
10176        public List<String> getCrossProfileWidgetProviders(int profileId) {
10177            synchronized (DevicePolicyManagerService.this) {
10178                if (mOwners == null) {
10179                    return Collections.emptyList();
10180                }
10181                ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
10182                if (ownerComponent == null) {
10183                    return Collections.emptyList();
10184                }
10185
10186                DevicePolicyData policy = getUserDataUnchecked(profileId);
10187                ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
10188
10189                if (admin == null || admin.crossProfileWidgetProviders == null
10190                        || admin.crossProfileWidgetProviders.isEmpty()) {
10191                    return Collections.emptyList();
10192                }
10193
10194                return admin.crossProfileWidgetProviders;
10195            }
10196        }
10197
10198        @Override
10199        public void addOnCrossProfileWidgetProvidersChangeListener(
10200                OnCrossProfileWidgetProvidersChangeListener listener) {
10201            synchronized (DevicePolicyManagerService.this) {
10202                if (mWidgetProviderListeners == null) {
10203                    mWidgetProviderListeners = new ArrayList<>();
10204                }
10205                if (!mWidgetProviderListeners.contains(listener)) {
10206                    mWidgetProviderListeners.add(listener);
10207                }
10208            }
10209        }
10210
10211        @Override
10212        public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
10213            synchronized(DevicePolicyManagerService.this) {
10214                return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
10215            }
10216        }
10217
10218        private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
10219            final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
10220            synchronized (DevicePolicyManagerService.this) {
10221                listeners = new ArrayList<>(mWidgetProviderListeners);
10222            }
10223            final int listenerCount = listeners.size();
10224            for (int i = 0; i < listenerCount; i++) {
10225                OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
10226                listener.onCrossProfileWidgetProvidersChanged(userId, packages);
10227            }
10228        }
10229
10230        @Override
10231        public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
10232            // This method is called from AM with its lock held, so don't take the DPMS lock.
10233            // b/29242568
10234
10235            ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
10236            if (profileOwner != null) {
10237                return DevicePolicyManagerService.this
10238                        .createShowAdminSupportIntent(profileOwner, userId);
10239            }
10240
10241            final Pair<Integer, ComponentName> deviceOwner =
10242                    mOwners.getDeviceOwnerUserIdAndComponent();
10243            if (deviceOwner != null && deviceOwner.first == userId) {
10244                return DevicePolicyManagerService.this
10245                        .createShowAdminSupportIntent(deviceOwner.second, userId);
10246            }
10247
10248            // We're not specifying the device admin because there isn't one.
10249            if (useDefaultIfNoAdmin) {
10250                return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
10251            }
10252            return null;
10253        }
10254
10255        @Override
10256        public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
10257            int source;
10258            long ident = mInjector.binderClearCallingIdentity();
10259            try {
10260                source = mUserManager.getUserRestrictionSource(userRestriction,
10261                        UserHandle.of(userId));
10262            } finally {
10263                mInjector.binderRestoreCallingIdentity(ident);
10264            }
10265            if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) {
10266                /*
10267                 * In this case, the user restriction is enforced by the system.
10268                 * So we won't show an admin support intent, even if it is also
10269                 * enforced by a profile/device owner.
10270                 */
10271                return null;
10272            }
10273            boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0;
10274            boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0;
10275            if (enforcedByDo && enforcedByPo) {
10276                // In this case, we'll show an admin support dialog that does not
10277                // specify the admin.
10278                return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
10279            } else if (enforcedByPo) {
10280                final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
10281                if (profileOwner != null) {
10282                    return DevicePolicyManagerService.this
10283                            .createShowAdminSupportIntent(profileOwner, userId);
10284                }
10285                // This could happen if another thread has changed the profile owner since we called
10286                // getUserRestrictionSource
10287                return null;
10288            } else if (enforcedByDo) {
10289                final Pair<Integer, ComponentName> deviceOwner
10290                        = mOwners.getDeviceOwnerUserIdAndComponent();
10291                if (deviceOwner != null) {
10292                    return DevicePolicyManagerService.this
10293                            .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first);
10294                }
10295                // This could happen if another thread has changed the device owner since we called
10296                // getUserRestrictionSource
10297                return null;
10298            }
10299            return null;
10300        }
10301
10302        @Override
10303        public boolean isUserAffiliatedWithDevice(int userId) {
10304            return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId);
10305        }
10306
10307        @Override
10308        public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) {
10309            synchronized (DevicePolicyManagerService.this) {
10310                updateMaximumTimeToLockLocked(userId);
10311            }
10312        }
10313
10314        @Override
10315        public boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) {
10316            return DevicePolicyManagerService.this.canUserHaveUntrustedCredentialReset(userId);
10317        }
10318
10319        @Override
10320        public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) {
10321            synchronized (DevicePolicyManagerService.this) {
10322                DevicePolicyData policy = getUserData(userId);
10323                if (policy.mPrintingEnabled) {
10324                    Log.e(LOG_TAG, "printing is enabled");
10325                    return null;
10326                }
10327                String ownerPackage = mOwners.getProfileOwnerPackage(userId);
10328                if (ownerPackage == null) {
10329                    ownerPackage = mOwners.getDeviceOwnerPackageName();
10330                }
10331                PackageManager pm = mInjector.getPackageManager();
10332                PackageInfo packageInfo;
10333                try {
10334                    packageInfo = pm.getPackageInfo(ownerPackage, 0);
10335                } catch (NameNotFoundException e) {
10336                    Log.e(LOG_TAG, "getPackageInfo error", e);
10337                    return null;
10338                }
10339                if (packageInfo == null) {
10340                    Log.e(LOG_TAG, "packageInfo is inexplicably null");
10341                    return null;
10342                }
10343                ApplicationInfo appInfo = packageInfo.applicationInfo;
10344                if (appInfo == null) {
10345                    Log.e(LOG_TAG, "appInfo is inexplicably null");
10346                    return null;
10347                }
10348                CharSequence appLabel = pm.getApplicationLabel(appInfo);
10349                if (appLabel == null) {
10350                    Log.e(LOG_TAG, "appLabel is inexplicably null");
10351                    return null;
10352                }
10353                return ((Context) ActivityThread.currentActivityThread().getSystemUiContext())
10354                        .getResources().getString(R.string.printing_disabled_by, appLabel);
10355            }
10356        }
10357    }
10358
10359    private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
10360        // This method is called with AMS lock held, so don't take DPMS lock
10361        final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
10362        intent.putExtra(Intent.EXTRA_USER_ID, userId);
10363        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
10364        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
10365        return intent;
10366    }
10367
10368    @Override
10369    public Intent createAdminSupportIntent(String restriction) {
10370        Preconditions.checkNotNull(restriction);
10371        final int uid = mInjector.binderGetCallingUid();
10372        final int userId = UserHandle.getUserId(uid);
10373        Intent intent = null;
10374        if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) ||
10375                DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction) ||
10376                DevicePolicyManager.POLICY_MANDATORY_BACKUPS.equals(restriction)) {
10377            synchronized(this) {
10378                final DevicePolicyData policy = getUserData(userId);
10379                final int N = policy.mAdminList.size();
10380                for (int i = 0; i < N; i++) {
10381                    final ActiveAdmin admin = policy.mAdminList.get(i);
10382                    if ((admin.disableCamera &&
10383                                DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) ||
10384                        (admin.disableScreenCapture && DevicePolicyManager
10385                                .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) ||
10386                        (admin.mandatoryBackupTransport != null && DevicePolicyManager
10387                                .POLICY_MANDATORY_BACKUPS.equals(restriction))) {
10388                        intent = createShowAdminSupportIntent(admin.info.getComponent(), userId);
10389                        break;
10390                    }
10391                }
10392                // For the camera, a device owner on a different user can disable it globally,
10393                // so we need an additional check.
10394                if (intent == null
10395                        && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
10396                    final ActiveAdmin admin = getDeviceOwnerAdminLocked();
10397                    if (admin != null && admin.disableCamera) {
10398                        intent = createShowAdminSupportIntent(admin.info.getComponent(),
10399                                mOwners.getDeviceOwnerUserId());
10400                    }
10401                }
10402            }
10403        } else {
10404            // if valid, |restriction| can only be a user restriction
10405            intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction);
10406        }
10407        if (intent != null) {
10408            intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
10409        }
10410        return intent;
10411    }
10412
10413    /**
10414     * Returns true if specified admin is allowed to limit passwords and has a
10415     * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
10416     */
10417    private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
10418        if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
10419            return false;
10420        }
10421        return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
10422    }
10423
10424    @Override
10425    public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
10426        if (policy != null && !policy.isValid()) {
10427            throw new IllegalArgumentException("Invalid system update policy.");
10428        }
10429        synchronized (this) {
10430            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10431            if (policy == null) {
10432                mOwners.clearSystemUpdatePolicy();
10433            } else {
10434                mOwners.setSystemUpdatePolicy(policy);
10435            }
10436            mOwners.writeDeviceOwner();
10437        }
10438        mContext.sendBroadcastAsUser(
10439                new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
10440                UserHandle.SYSTEM);
10441    }
10442
10443    @Override
10444    public SystemUpdatePolicy getSystemUpdatePolicy() {
10445        synchronized (this) {
10446            SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
10447            if (policy != null && !policy.isValid()) {
10448                Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
10449                return null;
10450            }
10451            return policy;
10452        }
10453    }
10454
10455    /**
10456     * Checks if the caller of the method is the device owner app.
10457     *
10458     * @param callerUid UID of the caller.
10459     * @return true if the caller is the device owner app
10460     */
10461    @VisibleForTesting
10462    boolean isCallerDeviceOwner(int callerUid) {
10463        synchronized (this) {
10464            if (!mOwners.hasDeviceOwner()) {
10465                return false;
10466            }
10467            if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
10468                return false;
10469            }
10470            final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
10471                    .getPackageName();
10472                try {
10473                    String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid);
10474                    for (String pkg : pkgs) {
10475                        if (deviceOwnerPackageName.equals(pkg)) {
10476                            return true;
10477                        }
10478                    }
10479                } catch (RemoteException e) {
10480                    return false;
10481                }
10482        }
10483
10484        return false;
10485    }
10486
10487    @Override
10488    public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
10489        mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
10490                "Only the system update service can broadcast update information");
10491
10492        if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
10493            Slog.w(LOG_TAG, "Only the system update service in the system user " +
10494                    "can broadcast update information.");
10495            return;
10496        }
10497
10498        if (!mOwners.saveSystemUpdateInfo(info)) {
10499            // Pending system update hasn't changed, don't send duplicate notification.
10500            return;
10501        }
10502
10503        final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
10504                .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
10505                        info == null ? -1 : info.getReceivedTime());
10506
10507        final long ident = mInjector.binderClearCallingIdentity();
10508        try {
10509            synchronized (this) {
10510                // Broadcast to device owner first if there is one.
10511                if (mOwners.hasDeviceOwner()) {
10512                    final UserHandle deviceOwnerUser =
10513                            UserHandle.of(mOwners.getDeviceOwnerUserId());
10514                    intent.setComponent(mOwners.getDeviceOwnerComponent());
10515                    mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
10516                }
10517            }
10518            // Get running users.
10519            final int runningUserIds[];
10520            try {
10521                runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
10522            } catch (RemoteException e) {
10523                // Shouldn't happen.
10524                Log.e(LOG_TAG, "Could not retrieve the list of running users", e);
10525                return;
10526            }
10527            // Send broadcasts to corresponding profile owners if any.
10528            for (final int userId : runningUserIds) {
10529                synchronized (this) {
10530                    final ComponentName profileOwnerPackage =
10531                            mOwners.getProfileOwnerComponent(userId);
10532                    if (profileOwnerPackage != null) {
10533                        intent.setComponent(profileOwnerPackage);
10534                        mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
10535                    }
10536                }
10537            }
10538        } finally {
10539            mInjector.binderRestoreCallingIdentity(ident);
10540        }
10541    }
10542
10543    @Override
10544    public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
10545        Preconditions.checkNotNull(admin, "ComponentName is null");
10546        enforceProfileOrDeviceOwner(admin);
10547
10548        return mOwners.getSystemUpdateInfo();
10549    }
10550
10551    @Override
10552    public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy)
10553            throws RemoteException {
10554        int userId = UserHandle.getCallingUserId();
10555        synchronized (this) {
10556            // Ensure the caller is a DO/PO or a permission grant state delegate.
10557            enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10558                    DELEGATION_PERMISSION_GRANT);
10559            DevicePolicyData userPolicy = getUserData(userId);
10560            if (userPolicy.mPermissionPolicy != policy) {
10561                userPolicy.mPermissionPolicy = policy;
10562                saveSettingsLocked(userId);
10563            }
10564        }
10565    }
10566
10567    @Override
10568    public int getPermissionPolicy(ComponentName admin) throws RemoteException {
10569        int userId = UserHandle.getCallingUserId();
10570        synchronized (this) {
10571            DevicePolicyData userPolicy = getUserData(userId);
10572            return userPolicy.mPermissionPolicy;
10573        }
10574    }
10575
10576    @Override
10577    public boolean setPermissionGrantState(ComponentName admin, String callerPackage,
10578            String packageName, String permission, int grantState) throws RemoteException {
10579        UserHandle user = mInjector.binderGetCallingUserHandle();
10580        synchronized (this) {
10581            // Ensure the caller is a DO/PO or a permission grant state delegate.
10582            enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10583                    DELEGATION_PERMISSION_GRANT);
10584            long ident = mInjector.binderClearCallingIdentity();
10585            try {
10586                if (getTargetSdk(packageName, user.getIdentifier())
10587                        < android.os.Build.VERSION_CODES.M) {
10588                    return false;
10589                }
10590                if (!isRuntimePermission(permission)) {
10591                    return false;
10592                }
10593                final PackageManager packageManager = mInjector.getPackageManager();
10594                switch (grantState) {
10595                    case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
10596                        mInjector.getPackageManagerInternal().grantRuntimePermission(packageName,
10597                                permission, user.getIdentifier(), true /* override policy */);
10598                        packageManager.updatePermissionFlags(permission, packageName,
10599                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
10600                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
10601                    } break;
10602
10603                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
10604                        mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName,
10605                                permission, user.getIdentifier(), true /* override policy */);
10606                        packageManager.updatePermissionFlags(permission, packageName,
10607                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
10608                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
10609                    } break;
10610
10611                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
10612                        packageManager.updatePermissionFlags(permission, packageName,
10613                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
10614                    } break;
10615                }
10616                return true;
10617            } catch (SecurityException se) {
10618                return false;
10619            } catch (NameNotFoundException e) {
10620                return false;
10621            } finally {
10622                mInjector.binderRestoreCallingIdentity(ident);
10623            }
10624        }
10625    }
10626
10627    @Override
10628    public int getPermissionGrantState(ComponentName admin, String callerPackage,
10629            String packageName, String permission) throws RemoteException {
10630        PackageManager packageManager = mInjector.getPackageManager();
10631
10632        UserHandle user = mInjector.binderGetCallingUserHandle();
10633        if (!isCallerWithSystemUid()) {
10634            // Ensure the caller is a DO/PO or a permission grant state delegate.
10635            enforceCanManageScope(admin, callerPackage,
10636                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT);
10637        }
10638        synchronized (this) {
10639            long ident = mInjector.binderClearCallingIdentity();
10640            try {
10641                int granted = mIPackageManager.checkPermission(permission,
10642                        packageName, user.getIdentifier());
10643                int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
10644                if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
10645                        != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
10646                    // Not controlled by policy
10647                    return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
10648                } else {
10649                    // Policy controlled so return result based on permission grant state
10650                    return granted == PackageManager.PERMISSION_GRANTED
10651                            ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
10652                            : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
10653                }
10654            } finally {
10655                mInjector.binderRestoreCallingIdentity(ident);
10656            }
10657        }
10658    }
10659
10660    boolean isPackageInstalledForUser(String packageName, int userHandle) {
10661        try {
10662            PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
10663                    userHandle);
10664            return (pi != null) && (pi.applicationInfo.flags != 0);
10665        } catch (RemoteException re) {
10666            throw new RuntimeException("Package manager has died", re);
10667        }
10668    }
10669
10670    public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
10671        final PackageManager packageManager = mInjector.getPackageManager();
10672        PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
10673        return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
10674                == PermissionInfo.PROTECTION_DANGEROUS;
10675    }
10676
10677    @Override
10678    public boolean isProvisioningAllowed(String action, String packageName) {
10679        Preconditions.checkNotNull(packageName);
10680
10681        final int callingUid = mInjector.binderGetCallingUid();
10682        final long ident = mInjector.binderClearCallingIdentity();
10683        try {
10684            final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser(
10685                    packageName, UserHandle.getUserId(callingUid));
10686            Preconditions.checkArgument(callingUid == uidForPackage,
10687                    "Caller uid doesn't match the one for the provided package.");
10688        } catch (NameNotFoundException e) {
10689            throw new IllegalArgumentException("Invalid package provided " + packageName, e);
10690        } finally {
10691            mInjector.binderRestoreCallingIdentity(ident);
10692        }
10693
10694        return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK;
10695    }
10696
10697    @Override
10698    public int checkProvisioningPreCondition(String action, String packageName) {
10699        Preconditions.checkNotNull(packageName);
10700        enforceCanManageProfileAndDeviceOwners();
10701        return checkProvisioningPreConditionSkipPermission(action, packageName);
10702    }
10703
10704    private int checkProvisioningPreConditionSkipPermission(String action, String packageName) {
10705        if (!mHasFeature) {
10706            return CODE_DEVICE_ADMIN_NOT_SUPPORTED;
10707        }
10708
10709        final int callingUserId = mInjector.userHandleGetCallingUserId();
10710        if (action != null) {
10711            switch (action) {
10712                case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
10713                    return checkManagedProfileProvisioningPreCondition(packageName, callingUserId);
10714                case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
10715                    return checkDeviceOwnerProvisioningPreCondition(callingUserId);
10716                case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER:
10717                    return checkManagedUserProvisioningPreCondition(callingUserId);
10718                case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE:
10719                    return checkManagedShareableDeviceProvisioningPreCondition(callingUserId);
10720            }
10721        }
10722        throw new IllegalArgumentException("Unknown provisioning action " + action);
10723    }
10724
10725    /**
10726     * The device owner can only be set before the setup phase of the primary user has completed,
10727     * except for adb command if no accounts or additional users are present on the device.
10728     */
10729    private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
10730            int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) {
10731        if (mOwners.hasDeviceOwner()) {
10732            return CODE_HAS_DEVICE_OWNER;
10733        }
10734        if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
10735            return CODE_USER_HAS_PROFILE_OWNER;
10736        }
10737        if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
10738            return CODE_USER_NOT_RUNNING;
10739        }
10740        if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
10741            return CODE_HAS_PAIRED;
10742        }
10743        if (isAdb) {
10744            // if shell command runs after user setup completed check device status. Otherwise, OK.
10745            if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
10746                if (!mInjector.userManagerIsSplitSystemUser()) {
10747                    if (mUserManager.getUserCount() > 1) {
10748                        return CODE_NONSYSTEM_USER_EXISTS;
10749                    }
10750                    if (hasIncompatibleAccountsOrNonAdb) {
10751                        return CODE_ACCOUNTS_NOT_EMPTY;
10752                    }
10753                } else {
10754                    // STOPSHIP Do proper check in split user mode
10755                }
10756            }
10757            return CODE_OK;
10758        } else {
10759            if (!mInjector.userManagerIsSplitSystemUser()) {
10760                // In non-split user mode, DO has to be user 0
10761                if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
10762                    return CODE_NOT_SYSTEM_USER;
10763                }
10764                // In non-split user mode, only provision DO before setup wizard completes
10765                if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
10766                    return CODE_USER_SETUP_COMPLETED;
10767                }
10768            } else {
10769                // STOPSHIP Do proper check in split user mode
10770            }
10771            return CODE_OK;
10772        }
10773    }
10774
10775    private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) {
10776        synchronized (this) {
10777            // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
10778            return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
10779                    deviceOwnerUserId, /* isAdb= */ false,
10780                    /* hasIncompatibleAccountsOrNonAdb=*/ true);
10781        }
10782    }
10783
10784    private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) {
10785        if (!hasFeatureManagedUsers()) {
10786            return CODE_MANAGED_USERS_NOT_SUPPORTED;
10787        }
10788        if (callingUserId == UserHandle.USER_SYSTEM
10789                && mInjector.userManagerIsSplitSystemUser()) {
10790            // Managed-profiles cannot be setup on the system user.
10791            return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
10792        }
10793        if (getProfileOwner(callingUserId) != null) {
10794            // Managed user cannot have a managed profile.
10795            return CODE_USER_HAS_PROFILE_OWNER;
10796        }
10797
10798        final long ident = mInjector.binderClearCallingIdentity();
10799        try {
10800            final UserHandle callingUserHandle = UserHandle.of(callingUserId);
10801            final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId);
10802            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
10803                    callingUserHandle)) {
10804                // An admin can initiate provisioning if it has set the restriction.
10805                if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
10806                        UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) {
10807                    return CODE_ADD_MANAGED_PROFILE_DISALLOWED;
10808                }
10809            }
10810            boolean canRemoveProfile = true;
10811            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
10812                    callingUserHandle)) {
10813                // We can remove a profile if the admin itself has set the restriction.
10814                if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
10815                        UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
10816                        callingUserId)) {
10817                    canRemoveProfile = false;
10818                }
10819            }
10820            if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) {
10821                return CODE_CANNOT_ADD_MANAGED_PROFILE;
10822            }
10823        } finally {
10824            mInjector.binderRestoreCallingIdentity(ident);
10825        }
10826        return CODE_OK;
10827    }
10828
10829    private ComponentName getOwnerComponent(String packageName, int userId) {
10830        if (isDeviceOwnerPackage(packageName, userId)) {
10831            return mOwners.getDeviceOwnerComponent();
10832        }
10833        if (isProfileOwnerPackage(packageName, userId)) {
10834            return mOwners.getProfileOwnerComponent(userId);
10835        }
10836        return null;
10837    }
10838
10839    /**
10840     * Return device owner or profile owner set on a given user.
10841     */
10842    private @Nullable ComponentName getOwnerComponent(int userId) {
10843        synchronized (this) {
10844            if (mOwners.getDeviceOwnerUserId() == userId) {
10845                return mOwners.getDeviceOwnerComponent();
10846            }
10847            if (mOwners.hasProfileOwner(userId)) {
10848                return mOwners.getProfileOwnerComponent(userId);
10849            }
10850        }
10851        return null;
10852    }
10853
10854    private int checkManagedUserProvisioningPreCondition(int callingUserId) {
10855        if (!hasFeatureManagedUsers()) {
10856            return CODE_MANAGED_USERS_NOT_SUPPORTED;
10857        }
10858        if (!mInjector.userManagerIsSplitSystemUser()) {
10859            // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
10860            return CODE_NOT_SYSTEM_USER_SPLIT;
10861        }
10862        if (callingUserId == UserHandle.USER_SYSTEM) {
10863            // System user cannot be a managed user.
10864            return CODE_SYSTEM_USER;
10865        }
10866        if (hasUserSetupCompleted(callingUserId)) {
10867            return CODE_USER_SETUP_COMPLETED;
10868        }
10869        if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
10870            return CODE_HAS_PAIRED;
10871        }
10872        return CODE_OK;
10873    }
10874
10875    private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) {
10876        if (!mInjector.userManagerIsSplitSystemUser()) {
10877            // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
10878            return CODE_NOT_SYSTEM_USER_SPLIT;
10879        }
10880        return checkDeviceOwnerProvisioningPreCondition(callingUserId);
10881    }
10882
10883    private boolean hasFeatureManagedUsers() {
10884        try {
10885            return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
10886        } catch (RemoteException e) {
10887            return false;
10888        }
10889    }
10890
10891    @Override
10892    public String getWifiMacAddress(ComponentName admin) {
10893        // Make sure caller has DO.
10894        synchronized (this) {
10895            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10896        }
10897
10898        final long ident = mInjector.binderClearCallingIdentity();
10899        try {
10900            final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
10901            if (wifiInfo == null) {
10902                return null;
10903            }
10904            return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
10905        } finally {
10906            mInjector.binderRestoreCallingIdentity(ident);
10907        }
10908    }
10909
10910    /**
10911     * Returns the target sdk version number that the given packageName was built for
10912     * in the given user.
10913     */
10914    private int getTargetSdk(String packageName, int userId) {
10915        final ApplicationInfo ai;
10916        try {
10917            ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
10918            final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
10919            return targetSdkVersion;
10920        } catch (RemoteException e) {
10921            // Shouldn't happen
10922            return 0;
10923        }
10924    }
10925
10926    @Override
10927    public boolean isManagedProfile(ComponentName admin) {
10928        enforceProfileOrDeviceOwner(admin);
10929        return isManagedProfile(mInjector.userHandleGetCallingUserId());
10930    }
10931
10932    @Override
10933    public boolean isSystemOnlyUser(ComponentName admin) {
10934        synchronized (this) {
10935            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10936        }
10937        final int callingUserId = mInjector.userHandleGetCallingUserId();
10938        return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
10939    }
10940
10941    @Override
10942    public void reboot(ComponentName admin) {
10943        Preconditions.checkNotNull(admin);
10944        // Make sure caller has DO.
10945        synchronized (this) {
10946            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10947        }
10948        long ident = mInjector.binderClearCallingIdentity();
10949        try {
10950            // Make sure there are no ongoing calls on the device.
10951            if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
10952                throw new IllegalStateException("Cannot be called with ongoing call on the device");
10953            }
10954            mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
10955        } finally {
10956            mInjector.binderRestoreCallingIdentity(ident);
10957        }
10958    }
10959
10960    @Override
10961    public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
10962        if (!mHasFeature) {
10963            return;
10964        }
10965        Preconditions.checkNotNull(who, "ComponentName is null");
10966        final int userHandle = mInjector.userHandleGetCallingUserId();
10967        synchronized (this) {
10968            ActiveAdmin admin = getActiveAdminForUidLocked(who,
10969                    mInjector.binderGetCallingUid());
10970            if (!TextUtils.equals(admin.shortSupportMessage, message)) {
10971                admin.shortSupportMessage = message;
10972                saveSettingsLocked(userHandle);
10973            }
10974        }
10975    }
10976
10977    @Override
10978    public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
10979        if (!mHasFeature) {
10980            return null;
10981        }
10982        Preconditions.checkNotNull(who, "ComponentName is null");
10983        synchronized (this) {
10984            ActiveAdmin admin = getActiveAdminForUidLocked(who,
10985                    mInjector.binderGetCallingUid());
10986            return admin.shortSupportMessage;
10987        }
10988    }
10989
10990    @Override
10991    public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
10992        if (!mHasFeature) {
10993            return;
10994        }
10995        Preconditions.checkNotNull(who, "ComponentName is null");
10996        final int userHandle = mInjector.userHandleGetCallingUserId();
10997        synchronized (this) {
10998            ActiveAdmin admin = getActiveAdminForUidLocked(who,
10999                    mInjector.binderGetCallingUid());
11000            if (!TextUtils.equals(admin.longSupportMessage, message)) {
11001                admin.longSupportMessage = message;
11002                saveSettingsLocked(userHandle);
11003            }
11004        }
11005    }
11006
11007    @Override
11008    public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
11009        if (!mHasFeature) {
11010            return null;
11011        }
11012        Preconditions.checkNotNull(who, "ComponentName is null");
11013        synchronized (this) {
11014            ActiveAdmin admin = getActiveAdminForUidLocked(who,
11015                    mInjector.binderGetCallingUid());
11016            return admin.longSupportMessage;
11017        }
11018    }
11019
11020    @Override
11021    public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
11022        if (!mHasFeature) {
11023            return null;
11024        }
11025        Preconditions.checkNotNull(who, "ComponentName is null");
11026        if (!isCallerWithSystemUid()) {
11027            throw new SecurityException("Only the system can query support message for user");
11028        }
11029        synchronized (this) {
11030            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
11031            if (admin != null) {
11032                return admin.shortSupportMessage;
11033            }
11034        }
11035        return null;
11036    }
11037
11038    @Override
11039    public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
11040        if (!mHasFeature) {
11041            return null;
11042        }
11043        Preconditions.checkNotNull(who, "ComponentName is null");
11044        if (!isCallerWithSystemUid()) {
11045            throw new SecurityException("Only the system can query support message for user");
11046        }
11047        synchronized (this) {
11048            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
11049            if (admin != null) {
11050                return admin.longSupportMessage;
11051            }
11052        }
11053        return null;
11054    }
11055
11056    @Override
11057    public void setOrganizationColor(@NonNull ComponentName who, int color) {
11058        if (!mHasFeature) {
11059            return;
11060        }
11061        Preconditions.checkNotNull(who, "ComponentName is null");
11062        final int userHandle = mInjector.userHandleGetCallingUserId();
11063        enforceManagedProfile(userHandle, "set organization color");
11064        synchronized (this) {
11065            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11066                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11067            admin.organizationColor = color;
11068            saveSettingsLocked(userHandle);
11069        }
11070    }
11071
11072    @Override
11073    public void setOrganizationColorForUser(int color, int userId) {
11074        if (!mHasFeature) {
11075            return;
11076        }
11077        enforceFullCrossUsersPermission(userId);
11078        enforceManageUsers();
11079        enforceManagedProfile(userId, "set organization color");
11080        synchronized (this) {
11081            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
11082            admin.organizationColor = color;
11083            saveSettingsLocked(userId);
11084        }
11085    }
11086
11087    @Override
11088    public int getOrganizationColor(@NonNull ComponentName who) {
11089        if (!mHasFeature) {
11090            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
11091        }
11092        Preconditions.checkNotNull(who, "ComponentName is null");
11093        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
11094        synchronized (this) {
11095            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11096                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11097            return admin.organizationColor;
11098        }
11099    }
11100
11101    @Override
11102    public int getOrganizationColorForUser(int userHandle) {
11103        if (!mHasFeature) {
11104            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
11105        }
11106        enforceFullCrossUsersPermission(userHandle);
11107        enforceManagedProfile(userHandle, "get organization color");
11108        synchronized (this) {
11109            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
11110            return (profileOwner != null)
11111                    ? profileOwner.organizationColor
11112                    : ActiveAdmin.DEF_ORGANIZATION_COLOR;
11113        }
11114    }
11115
11116    @Override
11117    public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
11118        if (!mHasFeature) {
11119            return;
11120        }
11121        Preconditions.checkNotNull(who, "ComponentName is null");
11122        final int userHandle = mInjector.userHandleGetCallingUserId();
11123
11124        synchronized (this) {
11125            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11126                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11127            if (!TextUtils.equals(admin.organizationName, text)) {
11128                admin.organizationName = (text == null || text.length() == 0)
11129                        ? null : text.toString();
11130                saveSettingsLocked(userHandle);
11131            }
11132        }
11133    }
11134
11135    @Override
11136    public CharSequence getOrganizationName(@NonNull ComponentName who) {
11137        if (!mHasFeature) {
11138            return null;
11139        }
11140        Preconditions.checkNotNull(who, "ComponentName is null");
11141        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
11142        synchronized(this) {
11143            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11144                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11145            return admin.organizationName;
11146        }
11147    }
11148
11149    @Override
11150    public CharSequence getDeviceOwnerOrganizationName() {
11151        if (!mHasFeature) {
11152            return null;
11153        }
11154        enforceDeviceOwnerOrManageUsers();
11155        synchronized(this) {
11156            final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
11157            return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
11158        }
11159    }
11160
11161    @Override
11162    public CharSequence getOrganizationNameForUser(int userHandle) {
11163        if (!mHasFeature) {
11164            return null;
11165        }
11166        enforceFullCrossUsersPermission(userHandle);
11167        enforceManagedProfile(userHandle, "get organization name");
11168        synchronized (this) {
11169            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
11170            return (profileOwner != null)
11171                    ? profileOwner.organizationName
11172                    : null;
11173        }
11174    }
11175
11176    @Override
11177    public List<String> setMeteredDataDisabled(ComponentName who, List<String> packageNames) {
11178        Preconditions.checkNotNull(who);
11179        Preconditions.checkNotNull(packageNames);
11180
11181        if (!mHasFeature) {
11182            return packageNames;
11183        }
11184        synchronized (this) {
11185            final ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11186                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11187            final int callingUserId = mInjector.userHandleGetCallingUserId();
11188            final long identity = mInjector.binderClearCallingIdentity();
11189            try {
11190                final List<String> excludedPkgs
11191                        = removeInvalidPkgsForMeteredDataRestriction(callingUserId, packageNames);
11192                admin.meteredDisabledPackages = packageNames;
11193                pushMeteredDisabledPackagesLocked(callingUserId);
11194                saveSettingsLocked(callingUserId);
11195                return excludedPkgs;
11196            } finally {
11197                mInjector.binderRestoreCallingIdentity(identity);
11198            }
11199        }
11200    }
11201
11202    private List<String> removeInvalidPkgsForMeteredDataRestriction(
11203            int userId, List<String> pkgNames) {
11204        final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId);
11205        final List<String> excludedPkgs = new ArrayList<>();
11206        for (int i = pkgNames.size() - 1; i >= 0; --i) {
11207            final String pkgName = pkgNames.get(i);
11208            // If the package is an active admin, don't restrict it.
11209            if (activeAdmins.contains(pkgName)) {
11210                excludedPkgs.add(pkgName);
11211                continue;
11212            }
11213            // If the package doesn't exist, don't restrict it.
11214            try {
11215                if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) {
11216                    excludedPkgs.add(pkgName);
11217                }
11218            } catch (RemoteException e) {
11219                // Should not happen
11220            }
11221        }
11222        pkgNames.removeAll(excludedPkgs);
11223        return excludedPkgs;
11224    }
11225
11226    @Override
11227    public List<String> getMeteredDataDisabled(ComponentName who) {
11228        Preconditions.checkNotNull(who);
11229
11230        if (!mHasFeature) {
11231            return new ArrayList<>();
11232        }
11233        synchronized (this) {
11234            final ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11235                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11236            return admin.meteredDisabledPackages == null
11237                    ? new ArrayList<>() : admin.meteredDisabledPackages;
11238        }
11239    }
11240
11241    private void pushMeteredDisabledPackagesLocked(int userId) {
11242        mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages(
11243                getMeteredDisabledPackagesLocked(userId), userId);
11244    }
11245
11246    private Set<String> getMeteredDisabledPackagesLocked(int userId) {
11247        final DevicePolicyData policy = getUserData(userId);
11248        final Set<String> restrictedPkgs = new ArraySet<>();
11249        for (int i = policy.mAdminList.size() - 1; i >= 0; --i) {
11250            final ActiveAdmin admin = policy.mAdminList.get(i);
11251            if (!isActiveAdminWithPolicyForUserLocked(admin,
11252                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, userId)) {
11253                // Not a profile or device owner, ignore
11254                continue;
11255            }
11256            if (admin.meteredDisabledPackages != null) {
11257                restrictedPkgs.addAll(admin.meteredDisabledPackages);
11258            }
11259        }
11260        return restrictedPkgs;
11261    }
11262
11263    @Override
11264    public void setAffiliationIds(ComponentName admin, List<String> ids) {
11265        if (!mHasFeature) {
11266            return;
11267        }
11268        if (ids == null) {
11269            throw new IllegalArgumentException("ids must not be null");
11270        }
11271        for (String id : ids) {
11272            if (TextUtils.isEmpty(id)) {
11273                throw new IllegalArgumentException("ids must not contain empty string");
11274            }
11275        }
11276
11277        final Set<String> affiliationIds = new ArraySet<>(ids);
11278        final int callingUserId = mInjector.userHandleGetCallingUserId();
11279        synchronized (this) {
11280            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11281            getUserData(callingUserId).mAffiliationIds = affiliationIds;
11282            saveSettingsLocked(callingUserId);
11283            if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
11284                // Affiliation ids specified by the device owner are additionally stored in
11285                // UserHandle.USER_SYSTEM's DevicePolicyData.
11286                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
11287                saveSettingsLocked(UserHandle.USER_SYSTEM);
11288            }
11289
11290            // Affiliation status for any user, not just the calling user, might have changed.
11291            // The device owner user will still be affiliated after changing its affiliation ids,
11292            // but as a result of that other users might become affiliated or un-affiliated.
11293            maybePauseDeviceWideLoggingLocked();
11294            maybeResumeDeviceWideLoggingLocked();
11295            maybeClearLockTaskPolicyLocked();
11296        }
11297    }
11298
11299    @Override
11300    public List<String> getAffiliationIds(ComponentName admin) {
11301        if (!mHasFeature) {
11302            return Collections.emptyList();
11303        }
11304
11305        Preconditions.checkNotNull(admin);
11306        synchronized (this) {
11307            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11308            return new ArrayList<String>(
11309                    getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds);
11310        }
11311    }
11312
11313    @Override
11314    public boolean isAffiliatedUser() {
11315        if (!mHasFeature) {
11316            return false;
11317        }
11318
11319        synchronized (this) {
11320            return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
11321        }
11322    }
11323
11324    private boolean isUserAffiliatedWithDeviceLocked(int userId) {
11325        if (!mOwners.hasDeviceOwner()) {
11326            return false;
11327        }
11328        if (userId == mOwners.getDeviceOwnerUserId()) {
11329            // The user that the DO is installed on is always affiliated with the device.
11330            return true;
11331        }
11332        if (userId == UserHandle.USER_SYSTEM) {
11333            // The system user is always affiliated in a DO device, even if the DO is set on a
11334            // different user. This could be the case if the DO is set in the primary user
11335            // of a split user device.
11336            return true;
11337        }
11338
11339        final ComponentName profileOwner = getProfileOwner(userId);
11340        if (profileOwner == null) {
11341            return false;
11342        }
11343
11344        final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
11345        final Set<String> deviceAffiliationIds =
11346                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
11347        for (String id : userAffiliationIds) {
11348            if (deviceAffiliationIds.contains(id)) {
11349                return true;
11350            }
11351        }
11352        return false;
11353    }
11354
11355    private boolean areAllUsersAffiliatedWithDeviceLocked() {
11356        final long ident = mInjector.binderClearCallingIdentity();
11357        try {
11358            final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
11359            for (int i = 0; i < userInfos.size(); i++) {
11360                int userId = userInfos.get(i).id;
11361                if (!isUserAffiliatedWithDeviceLocked(userId)) {
11362                    Slog.d(LOG_TAG, "User id " + userId + " not affiliated.");
11363                    return false;
11364                }
11365            }
11366        } finally {
11367            mInjector.binderRestoreCallingIdentity(ident);
11368        }
11369
11370        return true;
11371    }
11372
11373    @Override
11374    public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
11375        if (!mHasFeature) {
11376            return;
11377        }
11378        Preconditions.checkNotNull(admin);
11379
11380        synchronized (this) {
11381            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11382            if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
11383                return;
11384            }
11385            mInjector.securityLogSetLoggingEnabledProperty(enabled);
11386            if (enabled) {
11387                mSecurityLogMonitor.start();
11388                maybePauseDeviceWideLoggingLocked();
11389            } else {
11390                mSecurityLogMonitor.stop();
11391            }
11392        }
11393    }
11394
11395    @Override
11396    public boolean isSecurityLoggingEnabled(ComponentName admin) {
11397        if (!mHasFeature) {
11398            return false;
11399        }
11400
11401        synchronized (this) {
11402            if (!isCallerWithSystemUid()) {
11403                Preconditions.checkNotNull(admin);
11404                getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11405            }
11406            return mInjector.securityLogGetLoggingEnabledProperty();
11407        }
11408    }
11409
11410    private synchronized void recordSecurityLogRetrievalTime() {
11411        final long currentTime = System.currentTimeMillis();
11412        DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
11413        if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
11414            policyData.mLastSecurityLogRetrievalTime = currentTime;
11415            saveSettingsLocked(UserHandle.USER_SYSTEM);
11416        }
11417    }
11418
11419    @Override
11420    public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
11421        if (!mHasFeature) {
11422            return null;
11423        }
11424
11425        Preconditions.checkNotNull(admin);
11426        ensureDeviceOwnerAndAllUsersAffiliated(admin);
11427
11428        if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
11429                || !mInjector.securityLogGetLoggingEnabledProperty()) {
11430            return null;
11431        }
11432
11433        recordSecurityLogRetrievalTime();
11434
11435        ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
11436        try {
11437            SecurityLog.readPreviousEvents(output);
11438            return new ParceledListSlice<SecurityEvent>(output);
11439        } catch (IOException e) {
11440            Slog.w(LOG_TAG, "Fail to read previous events" , e);
11441            return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
11442        }
11443    }
11444
11445    @Override
11446    public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
11447        if (!mHasFeature) {
11448            return null;
11449        }
11450
11451        Preconditions.checkNotNull(admin);
11452        ensureDeviceOwnerAndAllUsersAffiliated(admin);
11453
11454        if (!mInjector.securityLogGetLoggingEnabledProperty()) {
11455            return null;
11456        }
11457
11458        recordSecurityLogRetrievalTime();
11459
11460        List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
11461        return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
11462    }
11463
11464    private void enforceCanManageDeviceAdmin() {
11465        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
11466                null);
11467    }
11468
11469    private void enforceCanManageProfileAndDeviceOwners() {
11470        mContext.enforceCallingOrSelfPermission(
11471                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
11472    }
11473
11474    private void enforceCallerSystemUserHandle() {
11475        final int callingUid = mInjector.binderGetCallingUid();
11476        final int userId = UserHandle.getUserId(callingUid);
11477        if (userId != UserHandle.USER_SYSTEM) {
11478            throw new SecurityException("Caller has to be in user 0");
11479        }
11480    }
11481
11482    @Override
11483    public boolean isUninstallInQueue(final String packageName) {
11484        enforceCanManageDeviceAdmin();
11485        final int userId = mInjector.userHandleGetCallingUserId();
11486        Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
11487        synchronized (this) {
11488            return mPackagesToRemove.contains(packageUserPair);
11489        }
11490    }
11491
11492    @Override
11493    public void uninstallPackageWithActiveAdmins(final String packageName) {
11494        enforceCanManageDeviceAdmin();
11495        Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
11496
11497        final int userId = mInjector.userHandleGetCallingUserId();
11498
11499        enforceUserUnlocked(userId);
11500
11501        final ComponentName profileOwner = getProfileOwner(userId);
11502        if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
11503            throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
11504        }
11505
11506        final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
11507        if (getDeviceOwnerUserId() == userId && deviceOwner != null
11508                && packageName.equals(deviceOwner.getPackageName())) {
11509            throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
11510        }
11511
11512        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
11513        synchronized (this) {
11514            mPackagesToRemove.add(packageUserPair);
11515        }
11516
11517        // All active admins on the user.
11518        final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
11519
11520        // Active admins in the target package.
11521        final List<ComponentName> packageActiveAdmins = new ArrayList<>();
11522        if (allActiveAdmins != null) {
11523            for (ComponentName activeAdmin : allActiveAdmins) {
11524                if (packageName.equals(activeAdmin.getPackageName())) {
11525                    packageActiveAdmins.add(activeAdmin);
11526                    removeActiveAdmin(activeAdmin, userId);
11527                }
11528            }
11529        }
11530        if (packageActiveAdmins.size() == 0) {
11531            startUninstallIntent(packageName, userId);
11532        } else {
11533            mHandler.postDelayed(new Runnable() {
11534                @Override
11535                public void run() {
11536                    for (ComponentName activeAdmin : packageActiveAdmins) {
11537                        removeAdminArtifacts(activeAdmin, userId);
11538                    }
11539                    startUninstallIntent(packageName, userId);
11540                }
11541            }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
11542        }
11543    }
11544
11545    @Override
11546    public boolean isDeviceProvisioned() {
11547        synchronized (this) {
11548            return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
11549        }
11550    }
11551
11552    private boolean isCurrentUserDemo() {
11553        if (UserManager.isDeviceInDemoMode(mContext)) {
11554            final int userId = mInjector.userHandleGetCallingUserId();
11555            final long callingIdentity = mInjector.binderClearCallingIdentity();
11556            try {
11557                return mUserManager.getUserInfo(userId).isDemo();
11558            } finally {
11559                mInjector.binderRestoreCallingIdentity(callingIdentity);
11560            }
11561        }
11562        return false;
11563    }
11564
11565    private void removePackageIfRequired(final String packageName, final int userId) {
11566        if (!packageHasActiveAdmins(packageName, userId)) {
11567            // Will not do anything if uninstall was not requested or was already started.
11568            startUninstallIntent(packageName, userId);
11569        }
11570    }
11571
11572    private void startUninstallIntent(final String packageName, final int userId) {
11573        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
11574        synchronized (this) {
11575            if (!mPackagesToRemove.contains(packageUserPair)) {
11576                // Do nothing if uninstall was not requested or was already started.
11577                return;
11578            }
11579            mPackagesToRemove.remove(packageUserPair);
11580        }
11581        try {
11582            if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
11583                // Package does not exist. Nothing to do.
11584                return;
11585            }
11586        } catch (RemoteException re) {
11587            Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
11588        }
11589
11590        try { // force stop the package before uninstalling
11591            mInjector.getIActivityManager().forceStopPackage(packageName, userId);
11592        } catch (RemoteException re) {
11593            Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
11594        }
11595        final Uri packageURI = Uri.parse("package:" + packageName);
11596        final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
11597        uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
11598        mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
11599    }
11600
11601    /**
11602     * Removes the admin from the policy. Ideally called after the admin's
11603     * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
11604     *
11605     * @param adminReceiver The admin to remove
11606     * @param userHandle The user for which this admin has to be removed.
11607     */
11608    private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
11609        synchronized (this) {
11610            final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
11611            if (admin == null) {
11612                return;
11613            }
11614            final DevicePolicyData policy = getUserData(userHandle);
11615            final boolean doProxyCleanup = admin.info.usesPolicy(
11616                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
11617            policy.mAdminList.remove(admin);
11618            policy.mAdminMap.remove(adminReceiver);
11619            validatePasswordOwnerLocked(policy);
11620            if (doProxyCleanup) {
11621                resetGlobalProxyLocked(policy);
11622            }
11623            pushActiveAdminPackagesLocked(userHandle);
11624            pushMeteredDisabledPackagesLocked(userHandle);
11625            saveSettingsLocked(userHandle);
11626            updateMaximumTimeToLockLocked(userHandle);
11627            policy.mRemovingAdmins.remove(adminReceiver);
11628
11629            Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
11630        }
11631        // The removed admin might have disabled camera, so update user
11632        // restrictions.
11633        pushUserRestrictions(userHandle);
11634    }
11635
11636    @Override
11637    public void setDeviceProvisioningConfigApplied() {
11638        enforceManageUsers();
11639        synchronized (this) {
11640            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
11641            policy.mDeviceProvisioningConfigApplied = true;
11642            saveSettingsLocked(UserHandle.USER_SYSTEM);
11643        }
11644    }
11645
11646    @Override
11647    public boolean isDeviceProvisioningConfigApplied() {
11648        enforceManageUsers();
11649        synchronized (this) {
11650            final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
11651            return policy.mDeviceProvisioningConfigApplied;
11652        }
11653    }
11654
11655    /**
11656     * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
11657     *
11658     * It's added for testing only. Please use this API carefully if it's used by other system app
11659     * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
11660     * apps.
11661     */
11662    @Override
11663    public void forceUpdateUserSetupComplete() {
11664        enforceCanManageProfileAndDeviceOwners();
11665        enforceCallerSystemUserHandle();
11666        // no effect if it's called from user build
11667        if (!mInjector.isBuildDebuggable()) {
11668            return;
11669        }
11670        final int userId = UserHandle.USER_SYSTEM;
11671        boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
11672                Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
11673        DevicePolicyData policy = getUserData(userId);
11674        policy.mUserSetupComplete = isUserCompleted;
11675        synchronized (this) {
11676            saveSettingsLocked(userId);
11677        }
11678    }
11679
11680    // TODO(b/22388012): When backup is available for secondary users and profiles, consider
11681    // whether there are any privacy/security implications of enabling the backup service here
11682    // if there are other users or profiles unmanaged or managed by a different entity (i.e. not
11683    // affiliated).
11684    @Override
11685    public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
11686        if (!mHasFeature) {
11687            return;
11688        }
11689        Preconditions.checkNotNull(admin);
11690        synchronized (this) {
11691            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(
11692                    admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11693            if (!enabled) {
11694                activeAdmin.mandatoryBackupTransport = null;
11695                saveSettingsLocked(UserHandle.USER_SYSTEM);
11696            }
11697        }
11698
11699        final long ident = mInjector.binderClearCallingIdentity();
11700        try {
11701            IBackupManager ibm = mInjector.getIBackupManager();
11702            if (ibm != null) {
11703                ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
11704            }
11705        } catch (RemoteException e) {
11706            throw new IllegalStateException(
11707                "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
11708        } finally {
11709            mInjector.binderRestoreCallingIdentity(ident);
11710        }
11711    }
11712
11713    @Override
11714    public boolean isBackupServiceEnabled(ComponentName admin) {
11715        Preconditions.checkNotNull(admin);
11716        if (!mHasFeature) {
11717            return true;
11718        }
11719        synchronized (this) {
11720            try {
11721                getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11722                IBackupManager ibm = mInjector.getIBackupManager();
11723                return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
11724            } catch (RemoteException e) {
11725                throw new IllegalStateException("Failed requesting backup service state.", e);
11726            }
11727        }
11728    }
11729
11730    @Override
11731    public void setMandatoryBackupTransport(
11732            ComponentName admin, ComponentName backupTransportComponent) {
11733        if (!mHasFeature) {
11734            return;
11735        }
11736        Preconditions.checkNotNull(admin);
11737        synchronized (this) {
11738            ActiveAdmin activeAdmin =
11739                    getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11740            if (!Objects.equals(backupTransportComponent, activeAdmin.mandatoryBackupTransport)) {
11741                activeAdmin.mandatoryBackupTransport = backupTransportComponent;
11742                saveSettingsLocked(UserHandle.USER_SYSTEM);
11743            }
11744        }
11745        final long identity = mInjector.binderClearCallingIdentity();
11746        try {
11747            IBackupManager ibm = mInjector.getIBackupManager();
11748            if (ibm != null && backupTransportComponent != null) {
11749                if (!ibm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11750                    ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, true);
11751                }
11752                ibm.selectBackupTransportAsync(backupTransportComponent, null);
11753                ibm.setBackupEnabled(true);
11754            }
11755        } catch (RemoteException e) {
11756            throw new IllegalStateException("Failed to set mandatory backup transport.", e);
11757        } finally {
11758            mInjector.binderRestoreCallingIdentity(identity);
11759        }
11760    }
11761
11762    @Override
11763    public ComponentName getMandatoryBackupTransport() {
11764        if (!mHasFeature) {
11765            return null;
11766        }
11767        synchronized (this) {
11768            ActiveAdmin activeAdmin = getDeviceOwnerAdminLocked();
11769            return activeAdmin == null ? null : activeAdmin.mandatoryBackupTransport;
11770        }
11771    }
11772
11773
11774    @Override
11775    public boolean bindDeviceAdminServiceAsUser(
11776            @NonNull ComponentName admin, @NonNull IApplicationThread caller,
11777            @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
11778            @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
11779        if (!mHasFeature) {
11780            return false;
11781        }
11782        Preconditions.checkNotNull(admin);
11783        Preconditions.checkNotNull(caller);
11784        Preconditions.checkNotNull(serviceIntent);
11785        Preconditions.checkArgument(
11786                serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
11787                "Service intent must be explicit (with a package name or component): "
11788                        + serviceIntent);
11789        Preconditions.checkNotNull(connection);
11790        Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
11791                "target user id must be different from the calling user id");
11792
11793        if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
11794            throw new SecurityException("Not allowed to bind to target user id");
11795        }
11796
11797        final String targetPackage;
11798        synchronized (this) {
11799            targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
11800        }
11801
11802        final long callingIdentity = mInjector.binderClearCallingIdentity();
11803        try {
11804            // Validate and sanitize the incoming service intent.
11805            final Intent sanitizedIntent =
11806                    createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
11807            if (sanitizedIntent == null) {
11808                // Fail, cannot lookup the target service.
11809                return false;
11810            }
11811            // Ask ActivityManager to bind it. Notice that we are binding the service with the
11812            // caller app instead of DevicePolicyManagerService.
11813            return mInjector.getIActivityManager().bindService(
11814                    caller, activtiyToken, serviceIntent,
11815                    serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
11816                    connection, flags, mContext.getOpPackageName(),
11817                    targetUserId) != 0;
11818        } catch (RemoteException ex) {
11819            // Same process, should not happen.
11820        } finally {
11821            mInjector.binderRestoreCallingIdentity(callingIdentity);
11822        }
11823
11824        // Failed to bind.
11825        return false;
11826    }
11827
11828    @Override
11829    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
11830        if (!mHasFeature) {
11831            return Collections.emptyList();
11832        }
11833        Preconditions.checkNotNull(admin);
11834
11835        synchronized (this) {
11836            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11837
11838            final int callingUserId = mInjector.userHandleGetCallingUserId();
11839            final long callingIdentity = mInjector.binderClearCallingIdentity();
11840            try {
11841                ArrayList<UserHandle> targetUsers = new ArrayList<>();
11842                if (!isDeviceOwner(admin, callingUserId)) {
11843                    // Profile owners can only bind to the device owner.
11844                    if (canUserBindToDeviceOwnerLocked(callingUserId)) {
11845                        targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
11846                    }
11847                } else {
11848                    // Caller is the device owner: Look for profile owners that it can bind to.
11849                    final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
11850                    for (int i = 0; i < userInfos.size(); i++) {
11851                        final int userId = userInfos.get(i).id;
11852                        if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
11853                            targetUsers.add(UserHandle.of(userId));
11854                        }
11855                    }
11856                }
11857
11858                return targetUsers;
11859            } finally {
11860                mInjector.binderRestoreCallingIdentity(callingIdentity);
11861            }
11862        }
11863    }
11864
11865    private boolean canUserBindToDeviceOwnerLocked(int userId) {
11866        // There has to be a device owner, under another user id.
11867        if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
11868            return false;
11869        }
11870
11871        // The user must have a profile owner that belongs to the same package as the device owner.
11872        if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
11873                mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
11874            return false;
11875        }
11876
11877        // The user must be affiliated.
11878        return isUserAffiliatedWithDeviceLocked(userId);
11879    }
11880
11881    /**
11882     * Return true if a given user has any accounts that'll prevent installing a device or profile
11883     * owner {@code owner}.
11884     * - If the user has no accounts, then return false.
11885     * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
11886     * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
11887     *   ..._DISALLOWED, return true.
11888     * - Otherwise return false.
11889     *
11890     * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
11891     * when the caller is not ADB.
11892     *
11893     * DO NOT CALL IT WITH THE DPMS LOCK HELD.
11894     */
11895    private boolean hasIncompatibleAccountsOrNonAdbNoLock(
11896            int userId, @Nullable ComponentName owner) {
11897        if (!isAdb()) {
11898            return true;
11899        }
11900        wtfIfInLock();
11901
11902        final long token = mInjector.binderClearCallingIdentity();
11903        try {
11904            final AccountManager am = AccountManager.get(mContext);
11905            final Account accounts[] = am.getAccountsAsUser(userId);
11906            if (accounts.length == 0) {
11907                return false;
11908            }
11909            synchronized (this) {
11910                if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
11911                    Log.w(LOG_TAG,
11912                            "Non test-only owner can't be installed with existing accounts.");
11913                    return true;
11914                }
11915            }
11916
11917            final String[] feature_allow =
11918                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
11919            final String[] feature_disallow =
11920                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
11921
11922            boolean compatible = true;
11923            for (Account account : accounts) {
11924                if (hasAccountFeatures(am, account, feature_disallow)) {
11925                    Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
11926                    compatible = false;
11927                    break;
11928                }
11929                if (!hasAccountFeatures(am, account, feature_allow)) {
11930                    Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
11931                    compatible = false;
11932                    break;
11933                }
11934            }
11935            if (compatible) {
11936                Log.w(LOG_TAG, "All accounts are compatible");
11937            } else {
11938                Log.e(LOG_TAG, "Found incompatible accounts");
11939            }
11940            return !compatible;
11941        } finally {
11942            mInjector.binderRestoreCallingIdentity(token);
11943        }
11944    }
11945
11946    private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
11947        try {
11948            return am.hasFeatures(account, features, null, null).getResult();
11949        } catch (Exception e) {
11950            Log.w(LOG_TAG, "Failed to get account feature", e);
11951            return false;
11952        }
11953    }
11954
11955    private boolean isAdb() {
11956        final int callingUid = mInjector.binderGetCallingUid();
11957        return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
11958    }
11959
11960    @Override
11961    public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
11962        if (!mHasFeature) {
11963            return;
11964        }
11965        Preconditions.checkNotNull(admin);
11966        getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11967
11968        if (enabled == isNetworkLoggingEnabledInternalLocked()) {
11969            // already in the requested state
11970            return;
11971        }
11972        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11973        deviceOwner.isNetworkLoggingEnabled = enabled;
11974        if (!enabled) {
11975            deviceOwner.numNetworkLoggingNotifications = 0;
11976            deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
11977        }
11978        saveSettingsLocked(mInjector.userHandleGetCallingUserId());
11979
11980        setNetworkLoggingActiveInternal(enabled);
11981    }
11982
11983    private synchronized void setNetworkLoggingActiveInternal(boolean active) {
11984        final long callingIdentity = mInjector.binderClearCallingIdentity();
11985        try {
11986            if (active) {
11987                mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
11988                if (!mNetworkLogger.startNetworkLogging()) {
11989                    mNetworkLogger = null;
11990                    Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
11991                            + " service not being available yet.");
11992                }
11993                maybePauseDeviceWideLoggingLocked();
11994                sendNetworkLoggingNotificationLocked();
11995            } else {
11996                if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
11997                    Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
11998                            + " service not being available yet.");
11999                }
12000                mNetworkLogger = null;
12001                mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING);
12002            }
12003        } finally {
12004            mInjector.binderRestoreCallingIdentity(callingIdentity);
12005        }
12006    }
12007
12008    /** Pauses security and network logging if there are unaffiliated users on the device */
12009    private void maybePauseDeviceWideLoggingLocked() {
12010        if (!areAllUsersAffiliatedWithDeviceLocked()) {
12011            Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be "
12012                    + "paused if enabled.");
12013            mSecurityLogMonitor.pause();
12014            if (mNetworkLogger != null) {
12015                mNetworkLogger.pause();
12016            }
12017        }
12018    }
12019
12020    /** Resumes security and network logging (if they are enabled) if all users are affiliated */
12021    private void maybeResumeDeviceWideLoggingLocked() {
12022        if (areAllUsersAffiliatedWithDeviceLocked()) {
12023            final long ident = mInjector.binderClearCallingIdentity();
12024            try {
12025                mSecurityLogMonitor.resume();
12026                if (mNetworkLogger != null) {
12027                    mNetworkLogger.resume();
12028                }
12029            } finally {
12030                mInjector.binderRestoreCallingIdentity(ident);
12031            }
12032        }
12033    }
12034
12035    /** Deletes any security and network logs that might have been collected so far */
12036    private void discardDeviceWideLogsLocked() {
12037        mSecurityLogMonitor.discardLogs();
12038        if (mNetworkLogger != null) {
12039            mNetworkLogger.discardLogs();
12040        }
12041        // TODO: We should discard pre-boot security logs here too, as otherwise those
12042        // logs (which might contain data from the user just removed) will be
12043        // available after next boot.
12044    }
12045
12046    @Override
12047    public boolean isNetworkLoggingEnabled(ComponentName admin) {
12048        if (!mHasFeature) {
12049            return false;
12050        }
12051        synchronized (this) {
12052            enforceDeviceOwnerOrManageUsers();
12053            return isNetworkLoggingEnabledInternalLocked();
12054        }
12055    }
12056
12057    private boolean isNetworkLoggingEnabledInternalLocked() {
12058        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
12059        return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
12060    }
12061
12062    /*
12063     * A maximum of 1200 events are returned, and the total marshalled size is in the order of
12064     * 100kB, so returning a List instead of ParceledListSlice is acceptable.
12065     * Ideally this would be done with ParceledList, however it only supports homogeneous types.
12066     *
12067     * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
12068     */
12069    @Override
12070    public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) {
12071        if (!mHasFeature) {
12072            return null;
12073        }
12074        Preconditions.checkNotNull(admin);
12075        ensureDeviceOwnerAndAllUsersAffiliated(admin);
12076
12077        synchronized (this) {
12078            if (mNetworkLogger == null
12079                    || !isNetworkLoggingEnabledInternalLocked()) {
12080                return null;
12081            }
12082
12083            final long currentTime = System.currentTimeMillis();
12084            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
12085            if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
12086                policyData.mLastNetworkLogsRetrievalTime = currentTime;
12087                saveSettingsLocked(UserHandle.USER_SYSTEM);
12088            }
12089            return mNetworkLogger.retrieveLogs(batchToken);
12090        }
12091    }
12092
12093    private void sendNetworkLoggingNotificationLocked() {
12094        final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
12095        if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
12096            return;
12097        }
12098        if (deviceOwner.numNetworkLoggingNotifications >=
12099                ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
12100            return;
12101        }
12102        final long now = System.currentTimeMillis();
12103        if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
12104            return;
12105        }
12106        deviceOwner.numNetworkLoggingNotifications++;
12107        if (deviceOwner.numNetworkLoggingNotifications
12108                >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
12109            deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
12110        } else {
12111            deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
12112        }
12113        final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
12114        intent.setPackage("com.android.systemui");
12115        final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
12116                UserHandle.CURRENT);
12117        Notification notification =
12118                new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
12119                .setSmallIcon(R.drawable.ic_info_outline)
12120                .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
12121                .setContentText(mContext.getString(R.string.network_logging_notification_text))
12122                .setTicker(mContext.getString(R.string.network_logging_notification_title))
12123                .setShowWhen(true)
12124                .setContentIntent(pendingIntent)
12125                .setStyle(new Notification.BigTextStyle()
12126                        .bigText(mContext.getString(R.string.network_logging_notification_text)))
12127                .build();
12128        mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification);
12129        saveSettingsLocked(mOwners.getDeviceOwnerUserId());
12130    }
12131
12132    /**
12133     * Return the package name of owner in a given user.
12134     */
12135    private String getOwnerPackageNameForUserLocked(int userId) {
12136        return mOwners.getDeviceOwnerUserId() == userId
12137                ? mOwners.getDeviceOwnerPackageName()
12138                : mOwners.getProfileOwnerPackage(userId);
12139    }
12140
12141    /**
12142     * @param rawIntent Original service intent specified by caller. It must be explicit.
12143     * @param expectedPackageName The expected package name of the resolved service.
12144     * @return Intent that have component explicitly set. {@code null} if no service is resolved
12145     *     with the given intent.
12146     * @throws SecurityException if the intent is resolved to an invalid service.
12147     */
12148    private Intent createCrossUserServiceIntent(
12149            @NonNull Intent rawIntent, @NonNull String expectedPackageName,
12150            @UserIdInt int targetUserId) throws RemoteException, SecurityException {
12151        ResolveInfo info = mIPackageManager.resolveService(
12152                rawIntent,
12153                rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
12154                0,  // flags
12155                targetUserId);
12156        if (info == null || info.serviceInfo == null) {
12157            Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent
12158                    + " or user " + targetUserId + " is not running");
12159            return null;
12160        }
12161        if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
12162            throw new SecurityException("Only allow to bind service in " + expectedPackageName);
12163        }
12164        // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
12165        if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
12166            throw new SecurityException(
12167                    "Service must be protected by BIND_DEVICE_ADMIN permission");
12168        }
12169        // It is the system server to bind the service, it would be extremely dangerous if it
12170        // can be exploited to bind any service. Set the component explicitly to make sure we
12171        // do not bind anything accidentally.
12172        rawIntent.setComponent(info.serviceInfo.getComponentName());
12173        return rawIntent;
12174    }
12175
12176    @Override
12177    public long getLastSecurityLogRetrievalTime() {
12178        enforceDeviceOwnerOrManageUsers();
12179        return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
12180     }
12181
12182    @Override
12183    public long getLastBugReportRequestTime() {
12184        enforceDeviceOwnerOrManageUsers();
12185        return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
12186     }
12187
12188    @Override
12189    public long getLastNetworkLogRetrievalTime() {
12190        enforceDeviceOwnerOrManageUsers();
12191        return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime;
12192    }
12193
12194    @Override
12195    public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
12196        if (!mHasFeature) {
12197            return false;
12198        }
12199        if (token == null || token.length < 32) {
12200            throw new IllegalArgumentException("token must be at least 32-byte long");
12201        }
12202        synchronized (this) {
12203            final int userHandle = mInjector.userHandleGetCallingUserId();
12204            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12205
12206            DevicePolicyData policy = getUserData(userHandle);
12207            long ident = mInjector.binderClearCallingIdentity();
12208            try {
12209                if (policy.mPasswordTokenHandle != 0) {
12210                    mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle);
12211                }
12212
12213                policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, userHandle);
12214                saveSettingsLocked(userHandle);
12215                return policy.mPasswordTokenHandle != 0;
12216            } finally {
12217                mInjector.binderRestoreCallingIdentity(ident);
12218            }
12219        }
12220    }
12221
12222    @Override
12223    public boolean clearResetPasswordToken(ComponentName admin) {
12224        if (!mHasFeature) {
12225            return false;
12226        }
12227        synchronized (this) {
12228            final int userHandle = mInjector.userHandleGetCallingUserId();
12229            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12230
12231            DevicePolicyData policy = getUserData(userHandle);
12232            if (policy.mPasswordTokenHandle != 0) {
12233                long ident = mInjector.binderClearCallingIdentity();
12234                try {
12235                    boolean result = mLockPatternUtils.removeEscrowToken(
12236                            policy.mPasswordTokenHandle, userHandle);
12237                    policy.mPasswordTokenHandle = 0;
12238                    saveSettingsLocked(userHandle);
12239                    return result;
12240                } finally {
12241                    mInjector.binderRestoreCallingIdentity(ident);
12242                }
12243            }
12244        }
12245        return false;
12246    }
12247
12248    @Override
12249    public boolean isResetPasswordTokenActive(ComponentName admin) {
12250        synchronized (this) {
12251            final int userHandle = mInjector.userHandleGetCallingUserId();
12252            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12253
12254            DevicePolicyData policy = getUserData(userHandle);
12255            if (policy.mPasswordTokenHandle != 0) {
12256                long ident = mInjector.binderClearCallingIdentity();
12257                try {
12258                    return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle,
12259                            userHandle);
12260                } finally {
12261                    mInjector.binderRestoreCallingIdentity(ident);
12262                }
12263            }
12264        }
12265        return false;
12266    }
12267
12268    @Override
12269    public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token,
12270            int flags) {
12271        Preconditions.checkNotNull(token);
12272        synchronized (this) {
12273            final int userHandle = mInjector.userHandleGetCallingUserId();
12274            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12275
12276            DevicePolicyData policy = getUserData(userHandle);
12277            if (policy.mPasswordTokenHandle != 0) {
12278                final String password = passwordOrNull != null ? passwordOrNull : "";
12279                return resetPasswordInternal(password, policy.mPasswordTokenHandle, token,
12280                        flags, mInjector.binderGetCallingUid(), userHandle);
12281            } else {
12282                Slog.w(LOG_TAG, "No saved token handle");
12283            }
12284        }
12285        return false;
12286    }
12287
12288    @Override
12289    public boolean isCurrentInputMethodSetByOwner() {
12290        enforceProfileOwnerOrSystemUser();
12291        return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet;
12292    }
12293
12294    @Override
12295    public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
12296        final int userId = user.getIdentifier();
12297        enforceProfileOwnerOrFullCrossUsersPermission(userId);
12298        synchronized (this) {
12299            return new StringParceledListSlice(
12300                    new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));
12301        }
12302    }
12303
12304    @Override
12305    public boolean clearApplicationUserData(ComponentName admin, String packageName,
12306            IPackageDataObserver callback) {
12307        Preconditions.checkNotNull(admin, "ComponentName is null");
12308        synchronized (this) {
12309            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12310        }
12311        final int userId = UserHandle.getCallingUserId();
12312
12313        long ident = mInjector.binderClearCallingIdentity();
12314        try {
12315            return ActivityManager.getService().clearApplicationUserData(packageName, false,
12316                    callback, userId);
12317        } catch(RemoteException re) {
12318            // Same process, should not happen.
12319        } catch (SecurityException se) {
12320            // This can happen e.g. for device admin packages, do not throw out the exception,
12321            // because callers have no means to know beforehand for which packages this might
12322            // happen.
12323            Slog.w(LOG_TAG, "Not allowed to clear application user data for package " + packageName,
12324                    se);
12325        } finally {
12326            mInjector.binderRestoreCallingIdentity(ident);
12327        }
12328
12329        if (callback != null) {
12330            try {
12331                // If there was a throw above, we send back that removal failed
12332                callback.onRemoveCompleted(packageName, false);
12333            } catch (RemoteException re) {
12334                // Caller is no longer available, ignore
12335            }
12336        }
12337        return false;
12338    }
12339
12340    @Override
12341    public synchronized void setLogoutEnabled(ComponentName admin, boolean enabled) {
12342        if (!mHasFeature) {
12343            return;
12344        }
12345        Preconditions.checkNotNull(admin);
12346
12347        synchronized (this) {
12348            ActiveAdmin deviceOwner =
12349                    getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12350
12351            if (deviceOwner.isLogoutEnabled == enabled) {
12352                // already in the requested state
12353                return;
12354            }
12355            deviceOwner.isLogoutEnabled = enabled;
12356            saveSettingsLocked(mInjector.userHandleGetCallingUserId());
12357        }
12358    }
12359
12360    @Override
12361    public boolean isLogoutEnabled() {
12362        if (!mHasFeature) {
12363            return false;
12364        }
12365        synchronized (this) {
12366            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
12367            return (deviceOwner != null) && deviceOwner.isLogoutEnabled;
12368        }
12369    }
12370
12371    @Override
12372    public List<String> getDisallowedSystemApps(ComponentName admin, int userId,
12373            String provisioningAction) throws RemoteException {
12374        enforceCanManageProfileAndDeviceOwners();
12375        return new ArrayList<>(
12376                mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction));
12377    }
12378
12379    @Override
12380    public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
12381            @Nullable PersistableBundle bundle) {
12382        if (!mHasFeature) {
12383            return;
12384        }
12385
12386        Preconditions.checkNotNull(admin, "Admin cannot be null.");
12387        Preconditions.checkNotNull(target, "Target cannot be null.");
12388
12389        enforceProfileOrDeviceOwner(admin);
12390
12391        if (admin.equals(target)) {
12392            throw new IllegalArgumentException("Provided administrator and target are "
12393                    + "the same object.");
12394        }
12395
12396        if (admin.getPackageName().equals(target.getPackageName())) {
12397            throw new IllegalArgumentException("Provided administrator and target have "
12398                    + "the same package name.");
12399        }
12400
12401        final int callingUserId = mInjector.userHandleGetCallingUserId();
12402        final DevicePolicyData policy = getUserData(callingUserId);
12403        final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId,
12404                /* throwForMissingPermission= */ true);
12405        checkActiveAdminPrecondition(target, incomingDeviceInfo, policy);
12406        if (!incomingDeviceInfo.getActivityInfo().metaData
12407                .getBoolean(DeviceAdminReceiver.SUPPORT_TRANSFER_OWNERSHIP_META_DATA, false)) {
12408            throw new IllegalArgumentException("Provided target does not support "
12409                    + "ownership transfer.");
12410        }
12411
12412        final long id = mInjector.binderClearCallingIdentity();
12413        try {
12414            synchronized (this) {
12415                /*
12416                * We must ensure the whole process is atomic to prevent the device from ending up
12417                * in an invalid state (e.g. no active admin). This could happen if the device
12418                * is rebooted or work mode is turned off mid-transfer.
12419                * In order to guarantee atomicity, we:
12420                *
12421                * 1. Save an atomic journal file describing the transfer process
12422                * 2. Perform the transfer itself
12423                * 3. Delete the journal file
12424                *
12425                * That way if the journal file exists on device boot, we know that the transfer
12426                * must be reverted back to the original administrator. This logic is implemented in
12427                * revertTransferOwnershipIfNecessaryLocked.
12428                * */
12429                if (bundle == null) {
12430                    bundle = new PersistableBundle();
12431                }
12432                if (isProfileOwner(admin, callingUserId)) {
12433                    prepareTransfer(admin, target, bundle, callingUserId,
12434                            ADMIN_TYPE_PROFILE_OWNER);
12435                    transferProfileOwnershipLocked(admin, target, callingUserId);
12436                    sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
12437                            getTransferOwnershipAdminExtras(bundle), callingUserId);
12438                    postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId);
12439                    if (isUserAffiliatedWithDeviceLocked(callingUserId)) {
12440                        notifyAffiliatedProfileTransferOwnershipComplete(callingUserId);
12441                    }
12442                } else if (isDeviceOwner(admin, callingUserId)) {
12443                    prepareTransfer(admin, target, bundle, callingUserId,
12444                            ADMIN_TYPE_DEVICE_OWNER);
12445                    transferDeviceOwnershipLocked(admin, target, callingUserId);
12446                    sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
12447                            getTransferOwnershipAdminExtras(bundle));
12448                    postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId);
12449                }
12450            }
12451        } finally {
12452            mInjector.binderRestoreCallingIdentity(id);
12453        }
12454    }
12455
12456    private void prepareTransfer(ComponentName admin, ComponentName target,
12457            PersistableBundle bundle, int callingUserId, String adminType) {
12458        saveTransferOwnershipBundleLocked(bundle, callingUserId);
12459        mTransferOwnershipMetadataManager.saveMetadataFile(
12460                new TransferOwnershipMetadataManager.Metadata(admin, target,
12461                        callingUserId, adminType));
12462    }
12463
12464    private void postTransfer(String broadcast, int callingUserId) {
12465        deleteTransferOwnershipMetadataFileLocked();
12466        sendOwnerChangedBroadcast(broadcast, callingUserId);
12467    }
12468
12469    private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) {
12470        final Bundle extras = new Bundle();
12471        extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId));
12472        sendDeviceOwnerCommand(
12473                DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras);
12474    }
12475
12476    /**
12477     * Transfers the profile owner for user with id profileOwnerUserId from admin to target.
12478     */
12479    private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target,
12480            int profileOwnerUserId) {
12481        transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId);
12482        mOwners.transferProfileOwner(target, profileOwnerUserId);
12483        Slog.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId);
12484        mOwners.writeProfileOwner(profileOwnerUserId);
12485        mDeviceAdminServiceController.startServiceForOwner(
12486                target.getPackageName(), profileOwnerUserId, "transfer-profile-owner");
12487    }
12488
12489    /**
12490     * Transfers the device owner for user with id userId from admin to target.
12491     */
12492    private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) {
12493        transferActiveAdminUncheckedLocked(target, admin, userId);
12494        mOwners.transferDeviceOwnership(target);
12495        Slog.i(LOG_TAG, "Device owner set: " + target + " on user " + userId);
12496        mOwners.writeDeviceOwner();
12497        mDeviceAdminServiceController.startServiceForOwner(
12498                target.getPackageName(), userId, "transfer-device-owner");
12499    }
12500
12501    private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) {
12502        Bundle extras = new Bundle();
12503        if (bundle != null) {
12504            extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle);
12505        }
12506        return extras;
12507    }
12508
12509    @Override
12510    public void setStartUserSessionMessage(
12511            ComponentName admin, CharSequence startUserSessionMessage) {
12512        if (!mHasFeature) {
12513            return;
12514        }
12515        Preconditions.checkNotNull(admin);
12516
12517        final String startUserSessionMessageString =
12518                startUserSessionMessage != null ? startUserSessionMessage.toString() : null;
12519
12520        synchronized (this) {
12521            final ActiveAdmin deviceOwner =
12522                    getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12523
12524            if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) {
12525                return;
12526            }
12527            deviceOwner.startUserSessionMessage = startUserSessionMessageString;
12528            saveSettingsLocked(mInjector.userHandleGetCallingUserId());
12529        }
12530
12531        mInjector.getActivityManagerInternal()
12532                .setSwitchingFromSystemUserMessage(startUserSessionMessageString);
12533    }
12534
12535    @Override
12536    public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) {
12537        if (!mHasFeature) {
12538            return;
12539        }
12540        Preconditions.checkNotNull(admin);
12541
12542        final String endUserSessionMessageString =
12543                endUserSessionMessage != null ? endUserSessionMessage.toString() : null;
12544
12545        synchronized (this) {
12546            final ActiveAdmin deviceOwner =
12547                    getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12548
12549            if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) {
12550                return;
12551            }
12552            deviceOwner.endUserSessionMessage = endUserSessionMessageString;
12553            saveSettingsLocked(mInjector.userHandleGetCallingUserId());
12554        }
12555
12556        mInjector.getActivityManagerInternal()
12557                .setSwitchingToSystemUserMessage(endUserSessionMessageString);
12558    }
12559
12560    @Override
12561    public String getStartUserSessionMessage(ComponentName admin) {
12562        if (!mHasFeature) {
12563            return null;
12564        }
12565        Preconditions.checkNotNull(admin);
12566
12567        synchronized (this) {
12568            final ActiveAdmin deviceOwner =
12569                    getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12570            return deviceOwner.startUserSessionMessage;
12571        }
12572    }
12573
12574    @Override
12575    public String getEndUserSessionMessage(ComponentName admin) {
12576        if (!mHasFeature) {
12577            return null;
12578        }
12579        Preconditions.checkNotNull(admin);
12580
12581        synchronized (this) {
12582            final ActiveAdmin deviceOwner =
12583                    getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12584            return deviceOwner.endUserSessionMessage;
12585        }
12586    }
12587
12588    private boolean hasPrinting() {
12589        return mInjector.getPackageManager().hasSystemFeature(PackageManager.FEATURE_PRINTING);
12590    }
12591
12592    @Override
12593    public void setPrintingEnabled(ComponentName admin, boolean enabled) {
12594        if (!mHasFeature || !hasPrinting()) {
12595            return;
12596        }
12597        Preconditions.checkNotNull(admin, "Admin cannot be null.");
12598        enforceProfileOrDeviceOwner(admin);
12599        synchronized (this) {
12600            final int userHandle = mInjector.userHandleGetCallingUserId();
12601            DevicePolicyData policy = getUserData(userHandle);
12602            if (policy.mPrintingEnabled != enabled) {
12603                policy.mPrintingEnabled = enabled;
12604                saveSettingsLocked(userHandle);
12605            }
12606        }
12607    }
12608
12609    private void deleteTransferOwnershipMetadataFileLocked() {
12610        mTransferOwnershipMetadataManager.deleteMetadataFile();
12611    }
12612
12613    @Override
12614    @Nullable
12615    public PersistableBundle getTransferOwnershipBundle() {
12616        synchronized (this) {
12617            final int callingUserId = mInjector.userHandleGetCallingUserId();
12618            getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12619            final File bundleFile = new File(
12620                    mInjector.environmentGetUserSystemDirectory(callingUserId),
12621                    TRANSFER_OWNERSHIP_PARAMETERS_XML);
12622            if (!bundleFile.exists()) {
12623                return null;
12624            }
12625            try (FileInputStream stream = new FileInputStream(bundleFile)) {
12626                XmlPullParser parser = Xml.newPullParser();
12627                parser.setInput(stream, null);
12628                return PersistableBundle.restoreFromXml(parser);
12629            } catch (IOException | XmlPullParserException | IllegalArgumentException e) {
12630                Slog.e(LOG_TAG, "Caught exception while trying to load the "
12631                        + "owner transfer parameters from file " + bundleFile, e);
12632                return null;
12633            }
12634        }
12635    }
12636
12637    /**
12638     * Returns whether printing is enabled for current user.
12639     * @hide
12640     */
12641    @Override
12642    public boolean isPrintingEnabled() {
12643        if (!hasPrinting()) {
12644            return false;
12645        }
12646        if (!mHasFeature) {
12647            return true;
12648        }
12649        synchronized (this) {
12650            final int userHandle = mInjector.userHandleGetCallingUserId();
12651            DevicePolicyData policy = getUserData(userHandle);
12652            return policy.mPrintingEnabled;
12653        }
12654    }
12655
12656    @Override
12657    public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) {
12658        if (!mHasFeature) {
12659            return -1;
12660        }
12661        Preconditions.checkNotNull(who, "ComponentName is null in addOverrideApn");
12662        Preconditions.checkNotNull(apnSetting, "ApnSetting is null in addOverrideApn");
12663        synchronized (this) {
12664            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12665        }
12666
12667        int operatedId = -1;
12668        Uri resultUri;
12669        final long id = mInjector.binderClearCallingIdentity();
12670        try {
12671            resultUri = mContext.getContentResolver().insert(DPC_URI, apnSetting.toContentValues());
12672        } finally {
12673            mInjector.binderRestoreCallingIdentity(id);
12674        }
12675        if (resultUri != null) {
12676            try {
12677                operatedId = Integer.parseInt(resultUri.getLastPathSegment());
12678            } catch (NumberFormatException e) {
12679                Slog.e(LOG_TAG, "Failed to parse inserted override APN id.", e);
12680            }
12681        }
12682
12683        return operatedId;
12684    }
12685
12686    @Override
12687    public boolean updateOverrideApn(@NonNull ComponentName who, int apnId,
12688            @NonNull ApnSetting apnSetting) {
12689        if (!mHasFeature) {
12690            return false;
12691        }
12692        Preconditions.checkNotNull(who, "ComponentName is null in updateOverrideApn");
12693        Preconditions.checkNotNull(apnSetting, "ApnSetting is null in updateOverrideApn");
12694        synchronized (this) {
12695            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12696        }
12697
12698        if (apnId < 0) {
12699            return false;
12700        }
12701        final long id = mInjector.binderClearCallingIdentity();
12702        try {
12703            return mContext.getContentResolver().update(
12704                    Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)),
12705                    apnSetting.toContentValues(), null, null) > 0;
12706        } finally {
12707            mInjector.binderRestoreCallingIdentity(id);
12708        }
12709    }
12710
12711    @Override
12712    public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) {
12713        if (!mHasFeature) {
12714            return false;
12715        }
12716        Preconditions.checkNotNull(who, "ComponentName is null in removeOverrideApn");
12717        synchronized (this) {
12718            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12719        }
12720
12721        return removeOverrideApnUnchecked(apnId);
12722    }
12723
12724    private boolean removeOverrideApnUnchecked(int apnId) {
12725        if(apnId < 0) {
12726            return false;
12727        }
12728        int numDeleted = 0;
12729        final long id = mInjector.binderClearCallingIdentity();
12730        try {
12731            numDeleted = mContext.getContentResolver().delete(
12732                    Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null);
12733        } finally {
12734            mInjector.binderRestoreCallingIdentity(id);
12735        }
12736        return numDeleted > 0;
12737    }
12738
12739    @Override
12740    public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) {
12741        if (!mHasFeature) {
12742            return Collections.emptyList();
12743        }
12744        Preconditions.checkNotNull(who, "ComponentName is null in getOverrideApns");
12745        synchronized (this) {
12746            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12747        }
12748
12749        return getOverrideApnsUnchecked();
12750    }
12751
12752    private List<ApnSetting> getOverrideApnsUnchecked() {
12753        final Cursor cursor;
12754        final long id = mInjector.binderClearCallingIdentity();
12755        try {
12756            cursor = mContext.getContentResolver().query(DPC_URI, null, null, null, null);
12757        } finally {
12758            mInjector.binderRestoreCallingIdentity(id);
12759        }
12760
12761        if (cursor == null) {
12762            return Collections.emptyList();
12763        }
12764        try {
12765            List<ApnSetting> apnList = new ArrayList<ApnSetting>();
12766            cursor.moveToPosition(-1);
12767            while (cursor.moveToNext()) {
12768                ApnSetting apn = ApnSetting.makeApnSetting(cursor);
12769                apnList.add(apn);
12770            }
12771            return apnList;
12772        } finally {
12773            cursor.close();
12774        }
12775    }
12776
12777    @Override
12778    public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) {
12779        if (!mHasFeature) {
12780            return;
12781        }
12782        Preconditions.checkNotNull(who, "ComponentName is null in setOverrideApnEnabled");
12783        synchronized (this) {
12784            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12785        }
12786
12787        setOverrideApnsEnabledUnchecked(enabled);
12788    }
12789
12790    private void setOverrideApnsEnabledUnchecked(boolean enabled) {
12791        ContentValues value = new ContentValues();
12792        value.put(ENFORCE_KEY, enabled);
12793        final long id = mInjector.binderClearCallingIdentity();
12794        try {
12795            mContext.getContentResolver().update(
12796                    ENFORCE_MANAGED_URI, value, null, null);
12797        } finally {
12798            mInjector.binderRestoreCallingIdentity(id);
12799        }
12800    }
12801
12802    @Override
12803    public boolean isOverrideApnEnabled(@NonNull ComponentName who) {
12804        if (!mHasFeature) {
12805            return false;
12806        }
12807        Preconditions.checkNotNull(who, "ComponentName is null in isOverrideApnEnabled");
12808        synchronized (this) {
12809            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12810        }
12811
12812        Cursor enforceCursor;
12813        final long id = mInjector.binderClearCallingIdentity();
12814        try {
12815            enforceCursor = mContext.getContentResolver().query(
12816                    ENFORCE_MANAGED_URI, null, null, null, null);
12817        } finally {
12818            mInjector.binderRestoreCallingIdentity(id);
12819        }
12820
12821        if (enforceCursor == null) {
12822            return false;
12823        }
12824        try {
12825            if (enforceCursor.moveToFirst()) {
12826                return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1;
12827            }
12828        } catch (IllegalArgumentException e) {
12829            Slog.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain "
12830                    + "correct info.", e);
12831        } finally {
12832            enforceCursor.close();
12833        }
12834        return false;
12835    }
12836
12837    @VisibleForTesting
12838    void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) {
12839        final File parametersFile = new File(
12840                mInjector.environmentGetUserSystemDirectory(userId),
12841                TRANSFER_OWNERSHIP_PARAMETERS_XML);
12842        final AtomicFile atomicFile = new AtomicFile(parametersFile);
12843        FileOutputStream stream = null;
12844        try {
12845            stream = atomicFile.startWrite();
12846            final XmlSerializer serializer = new FastXmlSerializer();
12847            serializer.setOutput(stream, StandardCharsets.UTF_8.name());
12848            serializer.startDocument(null, true);
12849            bundle.saveToXml(serializer);
12850            atomicFile.finishWrite(stream);
12851        } catch (IOException | XmlPullParserException e) {
12852            Slog.e(LOG_TAG, "Caught exception while trying to save the "
12853                    + "owner transfer parameters to file " + parametersFile, e);
12854            parametersFile.delete();
12855            atomicFile.failWrite(stream);
12856        }
12857    }
12858
12859    void deleteTransferOwnershipBundleLocked(int userId) {
12860        final File parametersFile = new File(mInjector.environmentGetUserSystemDirectory(userId),
12861                TRANSFER_OWNERSHIP_PARAMETERS_XML);
12862        parametersFile.delete();
12863    }
12864}
12865