OSDN Git Service

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