OSDN Git Service

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