OSDN Git Service

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