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