DevicePolicyManagerService.java revision 73145f4e60b874a408d26842d1cfc9c9506bfd9a
199e53b86eebb605b70dd7591b89bf61a9414ed0eGlenn Kasten/*
289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project * Copyright (C) 2010 The Android Open Source Project
389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project *
489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project * Licensed under the Apache License, Version 2.0 (the "License");
589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project * you may not use this file except in compliance with the License.
689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project * You may obtain a copy of the License at
789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project *
889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project *      http://www.apache.org/licenses/LICENSE-2.0
989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project *
1089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project * Unless required by applicable law or agreed to in writing, software
1189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project * distributed under the License is distributed on an "AS IS" BASIS,
1289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project * See the License for the specific language governing permissions and
1489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project * limitations under the License.
1589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project */
1689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectpackage com.android.server.devicepolicy;
1889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
2089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport static android.app.admin.DevicePolicyManager.CODE_ACCOUNTS_NOT_EMPTY;
2189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport static android.app.admin.DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED;
2289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport static android.app.admin.DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE;
239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport static android.app.admin.DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED;
249f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport static android.app.admin.DevicePolicyManager.CODE_HAS_DEVICE_OWNER;
2589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport static android.app.admin.DevicePolicyManager.CODE_HAS_PAIRED;
2689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport static android.app.admin.DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED;
279f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport static android.app.admin.DevicePolicyManager.CODE_NONSYSTEM_USER_EXISTS;
281ab85ec401801ef9a9184650d0f5a1639b45eeb9Glenn Kastenimport static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER;
29fce7a473248381cc83a01855f92581077d3c9ee2Dima Zavinimport static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT;
30b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgeraldimport static android.app.admin.DevicePolicyManager.CODE_OK;
31b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgeraldimport static android.app.admin.DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
32b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgeraldimport static android.app.admin.DevicePolicyManager.CODE_SYSTEM_USER;
33511754b5839fd9b09fc56b89ae007fbc39084a33Glenn Kastenimport static android.app.admin.DevicePolicyManager.CODE_USER_HAS_PROFILE_OWNER;
3489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport static android.app.admin.DevicePolicyManager.CODE_USER_NOT_RUNNING;
3533005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport static android.app.admin.DevicePolicyManager.CODE_USER_SETUP_COMPLETED;
3633005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
3733005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL;
3833005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
39e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kastenimport static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP;
40fff6d715a8db0daf08a50634f242c40268de3d49Glenn Kastenimport static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES;
4133005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS;
4233005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT;
43d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kastenimport static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
44d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kastenimport static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
45d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kastenimport static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
4604cd0186305e2b59d23c9147787046c6662029ccGlenn Kastenimport static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
47e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten
48e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kastenimport static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
49e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kastenimport static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
50e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kastenimport static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
51e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kastenimport static org.xmlpull.v1.XmlPullParser.END_TAG;
52e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kastenimport static org.xmlpull.v1.XmlPullParser.TEXT;
533b16c766d1ae2cfd8487e8ffb2b23936fc0a8e17Glenn Kasten
5466a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.Manifest.permission;
5566a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.accessibilityservice.AccessibilityServiceInfo;
5666a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.accounts.Account;
5770c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kastenimport android.accounts.AccountManager;
5870c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kastenimport android.annotation.NonNull;
5966a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.annotation.Nullable;
6033005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport android.annotation.UserIdInt;
61e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kastenimport android.app.Activity;
6266a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.app.ActivityManager;
6366a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.app.AlarmManager;
6470c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kastenimport android.app.AppGlobals;
6570c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kastenimport android.app.IActivityManager;
6666a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.app.IApplicationThread;
6733005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport android.app.IServiceConnection;
6833005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport android.app.Notification;
6966a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.app.NotificationManager;
7066a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.app.PendingIntent;
7170c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kastenimport android.app.StatusBarManager;
7270c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kastenimport android.app.admin.DeviceAdminInfo;
7366a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.app.admin.DeviceAdminReceiver;
7433005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport android.app.admin.DevicePolicyManager;
7533005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport android.app.admin.DevicePolicyManagerInternal;
7633005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport android.app.admin.IDevicePolicyManager;
7733005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport android.app.admin.NetworkEvent;
789f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport android.app.admin.PasswordMetrics;
799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport android.app.admin.SystemUpdateInfo;
809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport android.app.admin.SecurityLog;
8133005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport android.app.admin.SecurityLog.SecurityEvent;
8233005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport android.app.admin.SystemUpdatePolicy;
83e53b9ead781c36e96d6b6f012ddffc93a3d80f0dGlenn Kastenimport android.app.backup.IBackupManager;
8466a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.app.trust.TrustManager;
8566a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.content.BroadcastReceiver;
8666a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.content.ComponentName;
8766a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.content.Context;
8866a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.content.Intent;
8966a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.content.IntentFilter;
9066a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kastenimport android.content.pm.ActivityInfo;
913acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kastenimport android.content.pm.ApplicationInfo;
923acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kastenimport android.content.pm.IPackageManager;
9333005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport android.content.pm.PackageInfo;
9433005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehimport android.content.pm.PackageManager;
9589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.content.pm.PackageManager.NameNotFoundException;
9689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.content.pm.PackageManagerInternal;
9789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.content.pm.ParceledListSlice;
9889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.content.pm.ResolveInfo;
99879135196fd1c97deefc538c888037c56c2879a7Glenn Kastenimport android.content.pm.ServiceInfo;
1004ff14bae91075eb274eb1c2975982358946e7e63John Grossmanimport android.content.pm.UserInfo;
1014ff14bae91075eb274eb1c2975982358946e7e63John Grossmanimport android.database.ContentObserver;
1029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport android.graphics.Bitmap;
10389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.graphics.Color;
10489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.media.AudioManager;
10589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.media.IAudioService;
10689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.net.ConnectivityManager;
107fff6d715a8db0daf08a50634f242c40268de3d49Glenn Kastenimport android.net.IIpConnectivityMetrics;
10889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.net.ProxyInfo;
109e1c3962e268ffc12bfd1bd9ea84da1f135f36960Glenn Kastenimport android.net.Uri;
11028b76b334f92a15a2be3cc9e2f7d229a3275d1acGlenn Kastenimport android.net.metrics.IpConnectivityLog;
11189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.net.wifi.WifiInfo;
1120ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurentimport android.net.wifi.WifiManager;
11389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.os.AsyncTask;
11489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.os.Binder;
115be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurentimport android.os.Build;
1169f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport android.os.Bundle;
117ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgeraldimport android.os.Environment;
118462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissenimport android.os.FileUtils;
119d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissenimport android.os.Handler;
120d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissenimport android.os.IBinder;
121879135196fd1c97deefc538c888037c56c2879a7Glenn Kastenimport android.os.Looper;
1224ff14bae91075eb274eb1c2975982358946e7e63John Grossmanimport android.os.ParcelFileDescriptor;
1234ff14bae91075eb274eb1c2975982358946e7e63John Grossmanimport android.os.PersistableBundle;
1249f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport android.os.PowerManager;
12589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.os.PowerManagerInternal;
1260d255b2d9061ba31f13ada3fc0f7e51916407176Jean-Michel Triviimport android.os.Process;
127a514bdb58b5de4986679f72b7204b4764f7a2778Eric Laurentimport android.os.RecoverySystem;
128462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissenimport android.os.RemoteCallback;
129d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissenimport android.os.RemoteException;
13089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.os.ServiceManager;
13189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.os.SystemClock;
132c813985abd8ba61e999b3505f6a332574f87a1beAndreas Huberimport android.os.SystemProperties;
133fff6d715a8db0daf08a50634f242c40268de3d49Glenn Kastenimport android.os.UserHandle;
13489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.os.UserManager;
135e1c3962e268ffc12bfd1bd9ea84da1f135f36960Glenn Kastenimport android.os.UserManagerInternal;
13628b76b334f92a15a2be3cc9e2f7d229a3275d1acGlenn Kastenimport android.os.storage.StorageManager;
13789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.provider.ContactsContract.QuickContact;
1380ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurentimport android.provider.ContactsInternal;
13989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.provider.Settings;
14089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.security.Credentials;
141be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurentimport android.security.IKeyChainAliasCallback;
1429f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport android.security.IKeyChainService;
143ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgeraldimport android.security.KeyChain;
144462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissenimport android.security.KeyChain.KeyChainConnection;
145d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissenimport android.service.persistentdata.PersistentDataBlockManager;
146d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissenimport android.telephony.TelephonyManager;
147879135196fd1c97deefc538c888037c56c2879a7Glenn Kastenimport android.text.TextUtils;
1484ff14bae91075eb274eb1c2975982358946e7e63John Grossmanimport android.util.ArrayMap;
1494ff14bae91075eb274eb1c2975982358946e7e63John Grossmanimport android.util.ArraySet;
1509f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport android.util.Log;
15189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.util.Pair;
1520d255b2d9061ba31f13ada3fc0f7e51916407176Jean-Michel Triviimport android.util.Slog;
15317a736c3e1d062d7fc916329eb32aef8935614afGlenn Kastenimport android.util.SparseArray;
154d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissenimport android.util.Xml;
155d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissenimport android.view.IWindowManager;
15689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.view.accessibility.AccessibilityManager;
15789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.view.accessibility.IAccessibilityManager;
15889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.view.inputmethod.InputMethodInfo;
15989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport android.view.inputmethod.InputMethodManager;
16089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
16189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport com.android.internal.R;
16289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport com.android.internal.annotations.VisibleForTesting;
16389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport com.android.internal.logging.MetricsLogger;
16489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport com.android.internal.statusbar.IStatusBarService;
16589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport com.android.internal.util.FastXmlSerializer;
166b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgeraldimport com.android.internal.util.JournaledFile;
1673acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kastenimport com.android.internal.util.ParcelableString;
16889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport com.android.internal.util.Preconditions;
16989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport com.android.internal.util.XmlUtils;
17089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport com.android.internal.widget.LockPatternUtils;
17153cec22821072719ee02c856e9ac2dda2496c570Glenn Kastenimport com.android.server.LocalServices;
17253cec22821072719ee02c856e9ac2dda2496c570Glenn Kastenimport com.android.server.SystemService;
17389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
174d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissenimport com.android.server.pm.UserRestrictionsUtils;
175d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissenimport com.google.android.collect.Sets;
176d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen
17789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport org.xmlpull.v1.XmlPullParser;
17889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport org.xmlpull.v1.XmlPullParserException;
17989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport org.xmlpull.v1.XmlSerializer;
18089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
181fff6d715a8db0daf08a50634f242c40268de3d49Glenn Kastenimport java.io.ByteArrayInputStream;
18289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport java.io.File;
183e1c3962e268ffc12bfd1bd9ea84da1f135f36960Glenn Kastenimport java.io.FileDescriptor;
18428b76b334f92a15a2be3cc9e2f7d229a3275d1acGlenn Kastenimport java.io.FileInputStream;
185e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kastenimport java.io.FileNotFoundException;
1860ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurentimport java.io.FileOutputStream;
18789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport java.io.IOException;
18889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport java.io.PrintWriter;
18989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport java.nio.charset.StandardCharsets;
19089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport java.security.cert.CertificateException;
191be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurentimport java.security.cert.CertificateFactory;
1929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport java.security.cert.X509Certificate;
193ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgeraldimport java.text.DateFormat;
194462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissenimport java.util.ArrayList;
195d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissenimport java.util.Arrays;
196d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissenimport java.util.Collection;
19789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectimport java.util.Collections;
19886f04663032ddaa25110149d709bbf896ad83b02Glenn Kastenimport java.util.Date;
19986f04663032ddaa25110149d709bbf896ad83b02Glenn Kastenimport java.util.List;
20086f04663032ddaa25110149d709bbf896ad83b02Glenn Kastenimport java.util.Map.Entry;
20186f04663032ddaa25110149d709bbf896ad83b02Glenn Kastenimport java.util.Set;
20286f04663032ddaa25110149d709bbf896ad83b02Glenn Kastenimport java.util.concurrent.TimeUnit;
2039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenimport java.util.concurrent.atomic.AtomicBoolean;
2049f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2059f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten/**
2069f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten * Implementation of the device policy APIs.
2079f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten */
2089f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenpublic class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
2099f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2109f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String LOG_TAG = "DevicePolicyManager";
2119f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2129f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
2139f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2149f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String DEVICE_POLICIES_XML = "device_policies.xml";
2159f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2169f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
2179f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
2199f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2209f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String TAG_STATUS_BAR = "statusbar";
2219f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String ATTR_DISABLED = "disabled";
2239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2249f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String ATTR_NAME = "name";
2259f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2269f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
2279f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            "do-not-ask-credentials-on-boot";
2289f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2299f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String TAG_AFFILIATION_ID = "affiliation-id";
2309f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2319f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval";
2329f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2339f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request";
2349f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2359f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval";
236dd5f4c8c4059f890e81b28b026a688febb4e1dd9Glenn Kasten
2379f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
2389f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
239e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kasten    private static final String ATTR_ID = "id";
240e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kasten
241e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kasten    private static final String ATTR_VALUE = "value";
242e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kasten
243e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kasten    private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
244e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kasten
24589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    private static final int REQUEST_EXPIRE_PASSWORD = 5571;
24685ab62c4b433df3f1a9826bed1c9bec07a86c750Glenn Kasten
24785ab62c4b433df3f1a9826bed1c9bec07a86c750Glenn Kasten    private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);
24889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
249e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kasten    private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
2501a9ed11a472493cac7f6dfcbfac2064526a493edEric Laurent
2511703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
2529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
25353cec22821072719ee02c856e9ac2dda2496c570Glenn Kasten
2541dd70b9f04961a06fcb73a97fca10a53b3245d3cEric Laurent    private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
25529357bc2c0dd7c43ad3bd0c8e3efa4e6fd9bfd47Steve Block    private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
25689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    private static final int NETWORK_LOGGING_NOTIFICATION_ID = 1002;
25789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
25889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
25989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    private static final String ATTR_SETUP_COMPLETE = "setup-complete";
260fce7a473248381cc83a01855f92581077d3c9ee2Dima Zavin    private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
261fce7a473248381cc83a01855f92581077d3c9ee2Dima Zavin    private static final String ATTR_PERMISSION_POLICY = "permission-policy";
26289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
263dd5f4c8c4059f890e81b28b026a688febb4e1dd9Glenn Kasten            "device-provisioning-config-applied";
264dd5f4c8c4059f890e81b28b026a688febb4e1dd9Glenn Kasten    private static final String ATTR_DEVICE_PAIRED = "device-paired";
265dd5f4c8c4059f890e81b28b026a688febb4e1dd9Glenn Kasten    private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
266dd5f4c8c4059f890e81b28b026a688febb4e1dd9Glenn Kasten    private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
267dd5f4c8c4059f890e81b28b026a688febb4e1dd9Glenn Kasten            = "application-restrictions-manager";
268ea7939a079b3600cab955760839b021326f8cfc3Glenn Kasten
269b1bef51fec06e8bceec914d1b48b411d3ff2adffGlenn Kasten    // Comprehensive list of delegations.
27089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    private static final String DELEGATIONS[] = {
271b1bef51fec06e8bceec914d1b48b411d3ff2adffGlenn Kasten        DELEGATION_CERT_INSTALL,
272b1bef51fec06e8bceec914d1b48b411d3ff2adffGlenn Kasten        DELEGATION_APP_RESTRICTIONS,
273b1bef51fec06e8bceec914d1b48b411d3ff2adffGlenn Kasten        DELEGATION_BLOCK_UNINSTALL,
274b1bef51fec06e8bceec914d1b48b411d3ff2adffGlenn Kasten        DELEGATION_ENABLE_SYSTEM_APP,
275b1bef51fec06e8bceec914d1b48b411d3ff2adffGlenn Kasten        DELEGATION_KEEP_UNINSTALLED_PACKAGES,
276e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        DELEGATION_PACKAGE_ACCESS,
27789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        DELEGATION_PERMISSION_GRANT
278e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    };
279ea7939a079b3600cab955760839b021326f8cfc3Glenn Kasten
28089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    /**
281e1c3962e268ffc12bfd1bd9ea84da1f135f36960Glenn Kasten     *  System property whose value is either "true" or "false", indicating whether
282fce7a473248381cc83a01855f92581077d3c9ee2Dima Zavin     *  device owner is present.
28389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project     */
28489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
28589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
286fce7a473248381cc83a01855f92581077d3c9ee2Dima Zavin    private static final int STATUS_BAR_DISABLE_MASK =
287cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten            StatusBarManager.DISABLE_EXPAND |
28889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            StatusBarManager.DISABLE_NOTIFICATION_ICONS |
28989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
290dd5f4c8c4059f890e81b28b026a688febb4e1dd9Glenn Kasten            StatusBarManager.DISABLE_SEARCH;
291c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent
2928ba90326d683b035d99e24db669093e4602a7149Glenn Kasten    private static final int STATUS_BAR_DISABLE2_MASK =
2938ba90326d683b035d99e24db669093e4602a7149Glenn Kasten            StatusBarManager.DISABLE2_QUICK_SETTINGS;
2948ba90326d683b035d99e24db669093e4602a7149Glenn Kasten
2958ba90326d683b035d99e24db669093e4602a7149Glenn Kasten    private static final Set<String> SECURE_SETTINGS_WHITELIST;
296e3247bf8dd4f8fa8dfa3a108260241ae4a967569Glenn Kasten    private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
297e3247bf8dd4f8fa8dfa3a108260241ae4a967569Glenn Kasten    private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
298e3247bf8dd4f8fa8dfa3a108260241ae4a967569Glenn Kasten    private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
2998ba90326d683b035d99e24db669093e4602a7149Glenn Kasten    static {
300e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        SECURE_SETTINGS_WHITELIST = new ArraySet<>();
301e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
302e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
303e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
304e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten
305e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
306c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
307b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
308b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
309b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
310b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
311b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
312b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
3130ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurent        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
3143acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
3150ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurent        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
316c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
3171948eb3ea6eee336e8cdab9b0c693f93f5f19993Eric Laurent        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
3181948eb3ea6eee336e8cdab9b0c693f93f5f19993Eric Laurent
3191948eb3ea6eee336e8cdab9b0c693f93f5f19993Eric Laurent        GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
3201948eb3ea6eee336e8cdab9b0c693f93f5f19993Eric Laurent        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
321c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
322e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
323e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
324e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
325e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    }
326e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten
327e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    /**
328e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten     * Keyguard features that when set on a managed profile that doesn't have its own challenge will
329e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten     * affect the profile's parent user. These can also be set on the managed profile's parent DPM
330b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten     * instance.
331b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten     */
332b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten    private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
333b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten            DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
334b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten            | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
335b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten
336b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten    /**
337b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten     * Keyguard features that when set on a profile affect the profile content or challenge only.
338b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten     * These cannot be set on the managed profile's parent DPM instance
339b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten     */
34034f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
34134f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent            DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
34205632a5fa4b88ca474294887fc92a9fcdf0e2352Glenn Kasten
343396fabdb6efcdac5aea3d9f559d1beedf6a4cedcGlenn Kasten    /** Keyguard features that are allowed to be set on a managed profile */
344b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten    private static final int PROFILE_KEYGUARD_FEATURES =
345d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent            PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
3469f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
347be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent    private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
348d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen
349d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen    /**
350d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen     * Minimum timeout in milliseconds after which unlocking with weak auth times out,
351462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen     * i.e. the user has to use a strong authentication method like password, PIN or pattern.
352462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen     */
353462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
354462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
355d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen    /**
356d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen     * Strings logged with {@link
357d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen     * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}.
358d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen     */
359d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen    private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
3602beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent    private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
361093000f7d11839b920e8dfaa42ed1d09f48e24b8Glenn Kasten
3624a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten    final Context mContext;
363be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent    final Injector mInjector;
364a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten    final IPackageManager mIPackageManager;
365896adcd3ae6a1c7010e526327eff54e16179987bEric Laurent    final UserManager mUserManager;
366a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten    final UserManagerInternal mUserManagerInternal;
367a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten    final TelephonyManager mTelephonyManager;
368a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten    private final LockPatternUtils mLockPatternUtils;
36934f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent
370363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten    /**
371a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten     * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
37234f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent     * is requested for user u.
373a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten     */
374b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    private final Set<Pair<String, Integer>> mPackagesToRemove =
375b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            new ArraySet<Pair<String, Integer>>();
376a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten
377a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten    final LocalService mLocalService;
3782b2165c75790050810460c8de3f414876bce4c0eGlenn Kasten
37938e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    // Stores and loads state on device and profile owners.
38038e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    @VisibleForTesting
381b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    final Owners mOwners;
382b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
38338e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    private final Binder mToken = new Binder();
38438e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten
38538e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    /**
38638e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten     * Whether or not device admin feature is supported. If it isn't return defaults for all
38738e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten     * public methods.
38889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project     */
38989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    boolean mHasFeature;
39034f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent
39189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    /**
3929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten     * Whether or not this device is a watch.
39389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project     */
3949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    boolean mIsWatch;
39589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
3962c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi    private final SecurityLogMonitor mSecurityLogMonitor;
39789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    private NetworkLogger mNetworkLogger;
39889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
399d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen    private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
4009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
4019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
4039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        @Override
40489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        public void run() {
40589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            if(mRemoteBugreportServiceIsActive.get()) {
40689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                onBugreportFailed();
40789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            }
40889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
409b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    };
41089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
411f5aafb209d01ba2ab6cb55d1a12cfc653e2b4be0Eric Laurent    private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
412b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
4139f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        @Override
414b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        public void onReceive(Context context, Intent intent) {
4159f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
4161703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent                    && mRemoteBugreportServiceIsActive.get()) {
4179f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                onBugreportFinished(intent);
4182b584244930c9de0e3bc46898a801e9ccb731900Eric Laurent            }
4199f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
420b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    };
421b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
422b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
423b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
424b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        @Override
4259f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        public void onReceive(Context context, Intent intent) {
4269f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            String action = intent.getAction();
4279f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            mInjector.getNotificationManager().cancel(LOG_TAG,
428ec9a032c2e104ab1e3b5bf73e69dab1408ced0adEric Laurent                    RemoteBugreportUtils.NOTIFICATION_ID);
429ec9a032c2e104ab1e3b5bf73e69dab1408ced0adEric Laurent            if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
430ec9a032c2e104ab1e3b5bf73e69dab1408ced0adEric Laurent                onBugreportSharingAccepted();
43189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
4329f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                onBugreportSharingDeclined();
43396f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten            }
43489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
43589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
4369f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    };
437b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
438b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    public static final class Lifecycle extends SystemService {
439b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        private DevicePolicyManagerService mService;
440b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
441b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        public Lifecycle(Context context) {
4429f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            super(context);
4439f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            mService = new DevicePolicyManagerService(context);
4449f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
4459f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4469f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        @Override
44789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        public void onStart() {
4489f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
4499f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
4509f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        @Override
4529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        public void onBootPhase(int phase) {
45389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            mService.systemReady(phase);
4549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
4559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        @Override
4579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        public void onStartUser(int userHandle) {
4589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            mService.onStartUser(userHandle);
4599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
4609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
4619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
46289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    public static class DevicePolicyData {
463b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        @NonNull PasswordMetrics mActivePasswordMetrics = new PasswordMetrics();
464b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        int mFailedPasswordAttempts = 0;
465b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
46689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        int mUserHandle;
467879135196fd1c97deefc538c888037c56c2879a7Glenn Kasten        int mPasswordOwner = -1;
468a636433cbd09c0708b85f337ef45c0cdef3bcb4dGlenn Kasten        long mLastMaximumTimeToLock = -1;
46989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        boolean mUserSetupComplete = false;
47089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        boolean mPaired = false;
47189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        int mUserProvisioningState;
472b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        int mPermissionPolicy;
4739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4749f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean mDeviceProvisioningConfigApplied = false;
4759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4769f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
4779f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
478397edb3377e5775f4df60afb8bf6d4711e5adc0eGlenn Kasten        final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
4799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
4819f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
48223a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten        // This is the list of component allowed to start lock task mode.
483b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        List<String> mLockTaskPackages = new ArrayList<>();
484b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
485b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        boolean mStatusBarDisabled = false;
486b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
487b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        ComponentName mRestrictionsProvider;
4889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4899f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // Map of delegate package to delegation scopes
4909f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>();
4919f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean doNotAskCredentialsOnBoot = false;
4939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        Set<String> mAffiliationIds = new ArraySet<>();
4959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4969f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        long mLastSecurityLogRetrievalTime = -1;
4979f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
4989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        long mLastBugReportRequestTime = -1;
4999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
5009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        long mLastNetworkLogsRetrievalTime = -1;
501b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
5029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // Used for initialization of users created by createAndManageUsers.
5039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean mAdminBroadcastPending = false;
50423a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten        PersistableBundle mInitBundle = null;
505b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
506b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        public DevicePolicyData(int userHandle) {
5079f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            mUserHandle = userHandle;
5089f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
5099f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
5109f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
51189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
51289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
51389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    final Handler mHandler;
51489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
5159a2aaf927e56a4b4acab23ef16b3f133a9f48a63Glenn Kasten    BroadcastReceiver mReceiver = new BroadcastReceiver() {
5169f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        @Override
51789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        public void onReceive(Context context, Intent intent) {
51889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            final String action = intent.getAction();
51989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
52089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    getSendingUserId());
5219f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
5229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            /*
5239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten             * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
5241703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent             * however it's too early in the boot process to register with IIpConnectivityMetrics
5259f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten             * to listen for events.
5269f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten             */
5274bae3649d504d590a546717a8e49f96a30d9a745Glenn Kasten            if (Intent.ACTION_USER_STARTED.equals(action)
5289f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    && userHandle == mOwners.getDeviceOwnerUserId()) {
5291703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent                synchronized (DevicePolicyManagerService.this) {
5301703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent                    if (isNetworkLoggingEnabledInternalLocked()) {
5311703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent                        setNetworkLoggingActiveInternal(true);
5321703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent                    }
5339f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                }
534c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent            }
5352c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
5362c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi                    && userHandle == mOwners.getDeviceOwnerUserId()
5372c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi                    && getDeviceOwnerRemoteBugreportUri() != null) {
5382c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi                IntentFilter filterConsent = new IntentFilter();
539b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
540c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent                filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5419f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
54223a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten                mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
543b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                        RemoteBugreportUtils.NOTIFICATION_ID,
544b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                        RemoteBugreportUtils.buildNotification(mContext,
5459f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                                DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5464bae3649d504d590a546717a8e49f96a30d9a745Glenn Kasten                                UserHandle.ALL);
54789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            }
54889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
54989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
55089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                if (VERBOSE_LOG) {
551f5aafb209d01ba2ab6cb55d1a12cfc653e2b4be0Eric Laurent                    Slog.v(LOG_TAG, "Sending password expiration notifications for action "
552b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                            + action + " for user " + userHandle);
553b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                }
554b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                mHandler.post(new Runnable() {
555b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    @Override
556b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    public void run() {
5579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                        handlePasswordExpirationNotification(userHandle);
55889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    }
5599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                });
5609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
56189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            if (Intent.ACTION_USER_UNLOCKED.equals(action)
56289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    || Intent.ACTION_USER_STARTED.equals(action)
563be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                    || KeyChain.ACTION_TRUST_STORE_CHANGED.equals(action)) {
56489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                if (!StorageManager.inCryptKeeperBounce()) {
565f0c495012bad92230604a9a12a907812ec49ee8fGlenn Kasten                    new MonitoringCertNotificationTask().execute(
566be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                            intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL));
567be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                }
568be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent            }
5691703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent            if (Intent.ACTION_USER_ADDED.equals(action)) {
57089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
57189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                synchronized (DevicePolicyManagerService.this) {
57289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    // It might take a while for the user to become affiliated. Make security
573e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                    // and network logging unavailable in the meantime.
574be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                    maybePauseDeviceWideLoggingLocked();
57523a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten                }
57659fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
57759fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent                sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
578be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                synchronized (DevicePolicyManagerService.this) {
57989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    // Check whether the user is affiliated, *before* removing its data.
58089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
581b1c0993b215c5c3eebd1c6bafc22bba23d57a70bGlenn Kasten                    removeUserData(userHandle);
58289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    if (!isRemovedUserAffiliated) {
583b1c0993b215c5c3eebd1c6bafc22bba23d57a70bGlenn Kasten                        // We discard the logs when unaffiliated users are deleted (so that the
584be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                        // device owner cannot retrieve data about that user after it's gone).
585be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                        discardDeviceWideLogsLocked();
5862beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent                        // Resume logging if all remaining users are affiliated.
587be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                        maybeResumeDeviceWideLoggingLocked();
58805632a5fa4b88ca474294887fc92a9fcdf0e2352Glenn Kasten                    }
589be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                }
590be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent            } else if (Intent.ACTION_USER_STARTED.equals(action)) {
591be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                synchronized (DevicePolicyManagerService.this) {
5929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    // Reset the policy data
593be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                    mUserData.remove(userHandle);
594e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                    sendAdminEnabledBroadcastLocked(userHandle);
595be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                }
596be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                handlePackagesChanged(null /* check all admins */, userHandle);
597be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
598be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                handlePackagesChanged(null /* check all admins */, userHandle);
599a5224f319e2ba4b51ddb4287705ccf8d4b8ecc51Glenn Kasten            } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
600be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                    || (Intent.ACTION_PACKAGE_ADDED.equals(action)
601be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                            && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
6029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
603be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent            } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
60489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
60589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
6063b16c766d1ae2cfd8487e8ffb2b23936fc0a8e17Glenn Kasten            } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
60789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                clearWipeProfileNotification();
608b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            }
6094ff14bae91075eb274eb1c2975982358946e7e63John Grossman        }
6104ff14bae91075eb274eb1c2975982358946e7e63John Grossman
6114ff14bae91075eb274eb1c2975982358946e7e63John Grossman        private void sendUserAddedOrRemovedCommand(String action, int userHandle) {
6129f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            synchronized (DevicePolicyManagerService.this) {
61389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
614573266210fb2b2e7d86fbd46d0dfe16763611d91Eric Laurent                if (deviceOwner != null) {
61589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    Bundle extras = new Bundle();
61689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
617d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten                    sendAdminCommandLocked(deviceOwner, action, extras, null);
618d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten                }
619d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten            }
62089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
6211703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    };
622e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten
623e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    static class ActiveAdmin {
624e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten        private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
625573266210fb2b2e7d86fbd46d0dfe16763611d91Eric Laurent        private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
62689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_DISABLE_CAMERA = "disable-camera";
62789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
628a5224f319e2ba4b51ddb4287705ccf8d4b8ecc51Glenn Kasten        private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
62989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
6304ff14bae91075eb274eb1c2975982358946e7e63John Grossman                = "disable-bt-contacts-sharing";
6313b16c766d1ae2cfd8487e8ffb2b23936fc0a8e17Glenn Kasten        private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
6324ff14bae91075eb274eb1c2975982358946e7e63John Grossman        private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
6334ff14bae91075eb274eb1c2975982358946e7e63John Grossman        private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
6341703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent        private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
6356f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled";
6366f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        private static final String TAG_ACCOUNT_TYPE = "account-type";
6376f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
6386f59db12a64f4496866952a251122ccb77a36c6bEric Laurent                = "permitted-accessiblity-services";
63923a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten        private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
6406f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
6416f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
6426f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        private static final String TAG_TRUST_AGENT_COMPONENT = "component";
6436f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
6446f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
6456f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
6466f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
6476f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
648e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten        private static final String TAG_PERMITTED_IMES = "permitted-imes";
64989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
65089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
65189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
65289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
653b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
654083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten        private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
655083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten        private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
656083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten        private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
65789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
6589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
6599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
6609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String ATTR_VALUE = "value";
6619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String TAG_PASSWORD_QUALITY = "password-quality";
6629f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String TAG_POLICIES = "policies";
66389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
66489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                "cross-profile-widget-providers";
66589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_PROVIDER = "provider";
6669f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String TAG_PACKAGE_LIST_ITEM  = "item";
6679f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String TAG_KEEP_UNINSTALLED_PACKAGES  = "keep-uninstalled-packages";
6689f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
6699f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String TAG_DEFAULT_ENABLED_USER_RESTRICTIONS =
670c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent                "default-enabled-user-restrictions";
6719f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String TAG_RESTRICTION = "restriction";
67289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
67389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
67489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private static final String TAG_PARENT_ADMIN = "parent-admin";
6759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String TAG_ORGANIZATION_COLOR = "organization-color";
6769f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String TAG_ORGANIZATION_NAME = "organization-name";
6779f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification";
6789f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications";
6799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
6809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        final DeviceAdminInfo info;
6819f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
6829f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
6839f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
68489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
68589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
686fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten        static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
687b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
688d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
689d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
69089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
6919f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
69289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
6932c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi        @NonNull
69489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        PasswordMetrics minimumPasswordMetrics = new PasswordMetrics(
69589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH,
69689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE,
69789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC,
698a5224f319e2ba4b51ddb4287705ccf8d4b8ecc51Glenn Kasten                DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER);
69989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
700b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
701b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
702b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
703d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
704d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten
705d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
70689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
7079f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
70889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
70989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
71089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
71189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
71289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
71389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
71489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
715fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten
716b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
717d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten
718d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        boolean encryptionRequested = false;
71989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        boolean testOnlyAdmin = false;
7209f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean disableCamera = false;
7219f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean disableCallerId = false;
72289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        boolean disableContactsSearch = false;
7232b2165c75790050810460c8de3f414876bce4c0eGlenn Kasten        boolean disableBluetoothContactSharing = true;
72489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
72589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        boolean requireAutoTime = false; // Can only be set by a device owner.
72689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        boolean forceEphemeralUsers = false; // Can only be set by a device owner.
727a5224f319e2ba4b51ddb4287705ccf8d4b8ecc51Glenn Kasten        boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner.
72889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
729b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        // one notification after enabling + 3 more after reboots
730b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 4;
731b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        int numNetworkLoggingNotifications = 0;
732d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch
733d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten
734d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        ActiveAdmin parentAdmin;
73589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        final boolean isParent;
7369f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
73789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        static class TrustAgentInfo {
73889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            public PersistableBundle options;
73989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            TrustAgentInfo(PersistableBundle bundle) {
74089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                options = bundle;
74189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            }
74289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
74389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
744b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        final Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
745d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten
746d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        // The list of permitted accessibility services package namesas set by a profile
7479f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // or device owner. Null means all accessibility services are allowed, empty means
7489c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten        // none except system services are allowed.
7499c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten        List<String> permittedAccessiblityServices;
7509c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten
7519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // The list of permitted input methods package names as set by a profile or device owner.
7529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // Null means all input methods are allowed, empty means none except system imes are
7539f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // allowed.
7549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        List<String> permittedInputMethods;
7559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
7569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // List of package names to keep cached.
7579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        List<String> keepUninstalledPackages;
7589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
7599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // TODO: review implementation decisions with frameworks team
760d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        boolean specifiesGlobalProxy = false;
7619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        String globalProxySpec = null;
7629f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        String globalProxyExclusionList = null;
7639f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
7649f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
7659f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
766c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent        List<String> crossProfileWidgetProviders;
76789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
76889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        Bundle userRestrictions;
76989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
7709f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // User restrictions that have already been enabled by default for this admin (either when
77189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        // setting the device or profile owner, or during a system update if one of those "enabled
772d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        // by default" restrictions is newly added).
773d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        final Set<String> defaultEnabledRestrictionsAlreadySet = new ArraySet<>();
774d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten
7759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // Support text provided by the admin to display to the user.
7761703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent        CharSequence shortSupportMessage = null;
77723a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten        CharSequence longSupportMessage = null;
778b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
77989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        // Background color of confirm credentials screen. Default: teal.
780b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
781b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        int organizationColor = DEF_ORGANIZATION_COLOR;
782b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
783b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        // Default title of confirm credentials screen
784b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        String organizationName = null;
785b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
786b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
787b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            info = _info;
788b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            isParent = parent;
789b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
79089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
79189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        ActiveAdmin getParentActiveAdmin() {
79289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            Preconditions.checkState(!isParent);
793377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT
7949c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten            if (parentAdmin == null) {
7959c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten                parentAdmin = new ActiveAdmin(info, /* parent */ true);
7969c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten            }
7979c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten            return parentAdmin;
7989c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten        }
7999c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten
8009c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten        boolean hasParentActiveAdmin() {
8019c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten            return parentAdmin != null;
8029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
8039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
8049c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten        int getUid() { return info.getActivityInfo().applicationInfo.uid; }
8059c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten
8069c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten        public UserHandle getUserHandle() {
80789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
80889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
809b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
810083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten        void writeToXml(XmlSerializer out)
811083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten                throws IllegalArgumentException, IllegalStateException, IOException {
812083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten            out.startTag(null, TAG_POLICIES);
8131703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent            info.writePoliciesToXml(out);
8149f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            out.endTag(null, TAG_POLICIES);
8159f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            if (minimumPasswordMetrics.quality
816d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten                    != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
817d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten                out.startTag(null, TAG_PASSWORD_QUALITY);
8189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality));
8199f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                out.endTag(null, TAG_PASSWORD_QUALITY);
8209f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) {
8219f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
8229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    out.attribute(
82389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length));
82489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
82589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                }
82638e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
827c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent                    out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
8281703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent                    out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
829b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
8301703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent                }
8311703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent                if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
832be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                    out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
833be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                    out.attribute(
8349f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase));
8352beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent                    out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
8362beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent                }
8372beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent                if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
8382beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent                    out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
8392beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent                    out.attribute(
840be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase));
841be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                    out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
84289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                }
84389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) {
8441703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent                    out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
845363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                    out.attribute(
84634f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters));
84734f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                    out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
84834f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                }
84934f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
850e53b9ead781c36e96d6b6f012ddffc93a3d80f0dGlenn Kasten                    out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
851e53b9ead781c36e96d6b6f012ddffc93a3d80f0dGlenn Kasten                    out.attribute(
85234f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric));
85334f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                    out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
85438e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                }
85538e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
85638e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                    out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
85738e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                    out.attribute(
85838e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols));
85938e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                    out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
86038e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                }
86138e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
86238e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                    out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
86338e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                    out.attribute(
86438e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter));
86538e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                    out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
866ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                }
867ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten            }
868d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent            if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
869363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
870ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
8719f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
87238e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten            }
873d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent            if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
874d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent                out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
875ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
876363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
877ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten            }
878363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
87938e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
880ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
881ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
882ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten            }
883363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            if (specifiesGlobalProxy) {
884ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
885363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
88638e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
887ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                if (globalProxySpec != null) {
888ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                    out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
8894a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten                    out.attribute(null, ATTR_VALUE, globalProxySpec);
8904a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten                    out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
89143bdc1de363a3c72c7dcf9c9a898bac109dc7cb5Glenn Kasten                }
8924a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten                if (globalProxyExclusionList != null) {
8934a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten                    out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
894363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                    out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
895c6ba823a397abf865b02f4f48fe18231f94d8e87Glenn Kasten                    out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
896c6ba823a397abf865b02f4f48fe18231f94d8e87Glenn Kasten                }
89743bdc1de363a3c72c7dcf9c9a898bac109dc7cb5Glenn Kasten            }
89843bdc1de363a3c72c7dcf9c9a898bac109dc7cb5Glenn Kasten            if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
8993acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
900093000f7d11839b920e8dfaa42ed1d09f48e24b8Glenn Kasten                out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
901363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
9024a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten            }
903e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
9044a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten                out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
905ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
906b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten                out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
907b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten            }
908ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten            if (encryptionRequested) {
909ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.startTag(null, TAG_ENCRYPTION_REQUESTED);
910ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
911ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.endTag(null, TAG_ENCRYPTION_REQUESTED);
912363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            }
913ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten            if (testOnlyAdmin) {
914d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent                out.startTag(null, TAG_TEST_ONLY_ADMIN);
915e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
916363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                out.endTag(null, TAG_TEST_ONLY_ADMIN);
917363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            }
918e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            if (disableCamera) {
919363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                out.startTag(null, TAG_DISABLE_CAMERA);
920e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
921363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                out.endTag(null, TAG_DISABLE_CAMERA);
922e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            }
923e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            if (disableCallerId) {
924d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent                out.startTag(null, TAG_DISABLE_CALLER_ID);
925b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
926b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                out.endTag(null, TAG_DISABLE_CALLER_ID);
927b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            }
928363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            if (disableContactsSearch) {
929e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
930a42ff007a17d63df22c60dd5e5fd811ee45ca1b3Glenn Kasten                out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
931e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
932363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            }
933a42ff007a17d63df22c60dd5e5fd811ee45ca1b3Glenn Kasten            if (!disableBluetoothContactSharing) {
934e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
935e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.attribute(null, ATTR_VALUE,
936e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                        Boolean.toString(disableBluetoothContactSharing));
9371d6fa7af1288b550faabe4ec2cf98684236723dbNarayan Kamath                out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
938a42ff007a17d63df22c60dd5e5fd811ee45ca1b3Glenn Kasten            }
939363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            if (disableScreenCapture) {
94038e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
94138e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
942e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
943e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            }
944e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            if (requireAutoTime) {
945e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.startTag(null, TAG_REQUIRE_AUTO_TIME);
946e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
947e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.endTag(null, TAG_REQUIRE_AUTO_TIME);
948363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            }
949e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            if (forceEphemeralUsers) {
950363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
951e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
952e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
953e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            }
954d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent            if (isNetworkLoggingEnabled) {
955d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent                out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
956bb6f0a0bb413817d707cfb4c4a30847fda520787Glenn Kasten                out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled));
957bb6f0a0bb413817d707cfb4c4a30847fda520787Glenn Kasten                out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS,
958ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                        Integer.toString(numNetworkLoggingNotifications));
959ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION,
9607c027248e1a4ccd5b22bc4deafb03e2d87ac8f38Glenn Kasten                        Long.toString(lastNetworkLoggingNotificationTimeMs));
961d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent                out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
962363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            }
963e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kasten            if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
9643acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
965363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
966d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent                out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
967e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            }
968e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            if (!accountTypesWithManagementDisabled.isEmpty()) {
969ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
970e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                writeAttributeValuesToXml(
971e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                        out, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
972e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
973e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            }
974e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            if (!trustAgentInfos.isEmpty()) {
975ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
976ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
977ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                for (Entry<String, TrustAgentInfo> entry : set) {
978ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                    TrustAgentInfo trustAgentInfo = entry.getValue();
979e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                    out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
980e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                    out.attribute(null, ATTR_VALUE, entry.getKey());
981e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                    if (trustAgentInfo.options != null) {
982d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent                        out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
983d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent                        try {
984a075db4ff9b086ac2885df77bb6da0869293df92Glenn Kasten                            trustAgentInfo.options.saveToXml(out);
985a075db4ff9b086ac2885df77bb6da0869293df92Glenn Kasten                        } catch (XmlPullParserException e) {
986a075db4ff9b086ac2885df77bb6da0869293df92Glenn Kasten                            Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
987a075db4ff9b086ac2885df77bb6da0869293df92Glenn Kasten                        }
9883acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                        out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
9893acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                    }
990363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                    out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
9914a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten                }
9923acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
9933acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            }
9943acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
9954a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten                out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
9964a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten                writeAttributeValuesToXml(out, TAG_PROVIDER, crossProfileWidgetProviders);
997363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
998b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            }
999b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
1000b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    permittedAccessiblityServices);
100174935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten            writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
100274935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten            writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
1003363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            if (hasUserRestrictions()) {
1004363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                UserRestrictionsUtils.writeRestrictions(
100560a839204713e0f8258d082af83262b1eb33a6c3Glenn Kasten                        out, userRestrictions, TAG_USER_RESTRICTIONS);
1006363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            }
1007363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            if (!defaultEnabledRestrictionsAlreadySet.isEmpty()) {
1008a42ff007a17d63df22c60dd5e5fd811ee45ca1b3Glenn Kasten                out.startTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
100974935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten                writeAttributeValuesToXml(
1010e0b07179a48ee50fda931d2aa1b3c751d167e4d7Glenn Kasten                        out, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1011363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                out.endTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
101234f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent            }
10133acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            if (!TextUtils.isEmpty(shortSupportMessage)) {
1014be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1015d054c32443a493513ab63529b0c8b1aca290278cGlenn Kasten                out.text(shortSupportMessage.toString());
1016462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
101734f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent            }
101834f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent            if (!TextUtils.isEmpty(longSupportMessage)) {
1019c08d20b6a37122ebf116262c9372509ed060d4c1Glenn Kasten                out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
102029357bc2c0dd7c43ad3bd0c8e3efa4e6fd9bfd47Steve Block                out.text(longSupportMessage.toString());
102138e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
102234f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent            }
1023c08d20b6a37122ebf116262c9372509ed060d4c1Glenn Kasten            if (parentAdmin != null) {
1024c08d20b6a37122ebf116262c9372509ed060d4c1Glenn Kasten                out.startTag(null, TAG_PARENT_ADMIN);
102538e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                parentAdmin.writeToXml(out);
102638e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                out.endTag(null, TAG_PARENT_ADMIN);
102738e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten            }
1028d2c38fc4d5dc742d7441444316849510dd2b7363Glenn Kasten            if (organizationColor != DEF_ORGANIZATION_COLOR) {
1029d2c38fc4d5dc742d7441444316849510dd2b7363Glenn Kasten                out.startTag(null, TAG_ORGANIZATION_COLOR);
103029357bc2c0dd7c43ad3bd0c8e3efa4e6fd9bfd47Steve Block                out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
103134f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                out.endTag(null, TAG_ORGANIZATION_COLOR);
103234f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent            }
10330cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten            if (organizationName != null) {
10340cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten                out.startTag(null, TAG_ORGANIZATION_NAME);
10350cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten                out.text(organizationName);
10360cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten                out.endTag(null, TAG_ORGANIZATION_NAME);
10370cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten            }
103853cec22821072719ee02c856e9ac2dda2496c570Glenn Kasten        }
10399f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
10409f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        void writePackageListToXml(XmlSerializer out, String outerTag,
10419f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                List<String> packageList)
10429f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                throws IllegalArgumentException, IllegalStateException, IOException {
104334f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent            if (packageList == null) {
10445f631515d098c29603cda88f7a7e7580a2d55b57Glenn Kasten                return;
1045d2c38fc4d5dc742d7441444316849510dd2b7363Glenn Kasten            }
10460cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten
1047d2c38fc4d5dc742d7441444316849510dd2b7363Glenn Kasten            out.startTag(null, outerTag);
104874935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten            writeAttributeValuesToXml(out, TAG_PACKAGE_LIST_ITEM, packageList);
1049b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten            out.endTag(null, outerTag);
1050b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten        }
1051b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten
1052b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten        void writeAttributeValuesToXml(XmlSerializer out, String tag,
1053b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten                @NonNull Collection<String> values) throws IOException {
1054b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten            for (String value : values) {
1055b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten                out.startTag(null, tag);
10565f631515d098c29603cda88f7a7e7580a2d55b57Glenn Kasten                out.attribute(null, ATTR_VALUE, value);
1057a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten                out.endTag(null, tag);
1058363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            }
1059e0b07179a48ee50fda931d2aa1b3c751d167e4d7Glenn Kasten        }
1060b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten
1061a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        void readFromXml(XmlPullParser parser)
1062363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                throws XmlPullParserException, IOException {
1063b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten            int outerDepth = parser.getDepth();
1064b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten            int type;
1065b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten            while ((type=parser.next()) != END_DOCUMENT
1066b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten                   && (type != END_TAG || parser.getDepth() > outerDepth)) {
1067b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten                if (type == END_TAG || type == TEXT) {
10689f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    continue;
10699f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                }
10703acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                String tag = parser.getName();
1071b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten                if (TAG_POLICIES.equals(tag)) {
1072093000f7d11839b920e8dfaa42ed1d09f48e24b8Glenn Kasten                    info.readPoliciesFromXml(parser);
1073363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
1074363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                    minimumPasswordMetrics.quality = Integer.parseInt(
1075ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
1076ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten                } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
10779f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    minimumPasswordMetrics.length = Integer.parseInt(
10789f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
1079e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
10803acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                    passwordHistoryLength = Integer.parseInt(
1081363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
1082b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
1083b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    minimumPasswordMetrics.upperCase = Integer.parseInt(
1084b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                            parser.getAttributeValue(null, ATTR_VALUE));
1085b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
1086363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                    minimumPasswordMetrics.lowerCase = Integer.parseInt(
108738e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
108838e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
1089b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    minimumPasswordMetrics.letters = Integer.parseInt(
1090b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                            parser.getAttributeValue(null, ATTR_VALUE));
1091b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
109238e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                    minimumPasswordMetrics.numeric = Integer.parseInt(
109338e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
10949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
10959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    minimumPasswordMetrics.symbols = Integer.parseInt(
10969f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
10979f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
10989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    minimumPasswordMetrics.nonLetter = Integer.parseInt(
10999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
11009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
1101363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                    maximumTimeToUnlock = Long.parseLong(
11029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
110334f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
1104363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                    strongAuthUnlockTimeout = Long.parseLong(
110534f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                            parser.getAttributeValue(null, ATTR_VALUE));
110634f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
11072beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent                    maximumFailedPasswordsForWipe = Integer.parseInt(
1108e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
1109363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
11105f631515d098c29603cda88f7a7e7580a2d55b57Glenn Kasten                    specifiesGlobalProxy = Boolean.parseBoolean(
1111b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
1112093000f7d11839b920e8dfaa42ed1d09f48e24b8Glenn Kasten                } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1113093000f7d11839b920e8dfaa42ed1d09f48e24b8Glenn Kasten                    globalProxySpec =
1114b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten                        parser.getAttributeValue(null, ATTR_VALUE);
1115b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten                } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1116093000f7d11839b920e8dfaa42ed1d09f48e24b8Glenn Kasten                    globalProxyExclusionList =
1117e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                        parser.getAttributeValue(null, ATTR_VALUE);
1118e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1119363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                    passwordExpirationTimeout = Long.parseLong(
11209f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
11219f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
11229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    passwordExpirationDate = Long.parseLong(
11239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
11249f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
11259f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    encryptionRequested = Boolean.parseBoolean(
1126e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
1127e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1128e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                    testOnlyAdmin = Boolean.parseBoolean(
1129e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
11309f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_DISABLE_CAMERA.equals(tag)) {
11319f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    disableCamera = Boolean.parseBoolean(
11329f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
11339f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
11349f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    disableCallerId = Boolean.parseBoolean(
1135e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
113634f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
113738e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                    disableContactsSearch = Boolean.parseBoolean(
113838e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
113938e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
114038e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                    disableBluetoothContactSharing = Boolean.parseBoolean(parser
114138e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                            .getAttributeValue(null, ATTR_VALUE));
114238e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
114338e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                    disableScreenCapture = Boolean.parseBoolean(
114438e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
114534f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
114634f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                    requireAutoTime = Boolean.parseBoolean(
114789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                            parser.getAttributeValue(null, ATTR_VALUE));
114889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
11499f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    forceEphemeralUsers = Boolean.parseBoolean(
11509f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
11519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) {
11529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    isNetworkLoggingEnabled = Boolean.parseBoolean(
11539f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
11549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    lastNetworkLoggingNotificationTimeMs = Long.parseLong(
11559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION));
11569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    numNetworkLoggingNotifications = Integer.parseInt(
11579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS));
11589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
11599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    disabledKeyguardFeatures = Integer.parseInt(
1160df576995a5aad3428aeeef765387d650945c161dEric Laurent                            parser.getAttributeValue(null, ATTR_VALUE));
11619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
11629f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    readAttributeValues(
11639f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
11649f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
11659f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    trustAgentInfos = getAllTrustAgentInfos(parser, tag);
11669f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
11679f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    crossProfileWidgetProviders = new ArrayList<>();
11689f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    readAttributeValues(parser, TAG_PROVIDER, crossProfileWidgetProviders);
11699f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
11709f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    permittedAccessiblityServices = readPackageList(parser, tag);
11719f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_PERMITTED_IMES.equals(tag)) {
11729f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    permittedInputMethods = readPackageList(parser, tag);
11739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
11749f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    keepUninstalledPackages = readPackageList(parser, tag);
11759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
11769f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    userRestrictions = UserRestrictionsUtils.readRestrictions(parser);
11779f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) {
11789f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    readAttributeValues(
11799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
11809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
11819f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    type = parser.next();
11829f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    if (type == XmlPullParser.TEXT) {
1183e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                        shortSupportMessage = parser.getText();
11849f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    } else {
11859f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                        Log.w(LOG_TAG, "Missing text when loading short support message");
118689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    }
11879f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
11889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    type = parser.next();
118989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    if (type == XmlPullParser.TEXT) {
11909f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                        longSupportMessage = parser.getText();
11919f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    } else {
11929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                        Log.w(LOG_TAG, "Missing text when loading long support message");
11939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    }
11949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_PARENT_ADMIN.equals(tag)) {
119589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    Preconditions.checkState(!isParent);
11969f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
11979f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    parentAdmin = new ActiveAdmin(info, /* parent */ true);
11981703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent                    parentAdmin.readFromXml(parser);
11999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
12009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    organizationColor = Integer.parseInt(
12019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                            parser.getAttributeValue(null, ATTR_VALUE));
12029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
12039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    type = parser.next();
12049f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    if (type == XmlPullParser.TEXT) {
12059f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                        organizationName = parser.getText();
1206b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    } else {
1207b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                        Log.w(LOG_TAG, "Missing text when loading organization name");
1208b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    }
12099f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else {
121089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
121189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    XmlUtils.skipCurrentTag(parser);
12129f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                }
12139f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
1214c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent        }
12159f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
12169f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private List<String> readPackageList(XmlPullParser parser,
12179f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                String tag) throws XmlPullParserException, IOException {
12189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            List<String> result = new ArrayList<String>();
1219b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            int outerDepth = parser.getDepth();
1220b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            int outerType;
1221b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1222b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1223b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1224b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    continue;
1225b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                }
1226b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                String outerTag = parser.getName();
12279f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
12289f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    String packageName = parser.getAttributeValue(null, ATTR_VALUE);
12299f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    if (packageName != null) {
123089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                        result.add(packageName);
123189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    } else {
12329f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                        Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1233c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent                    }
12349f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else {
12359f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
12369f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                }
123789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            }
12389f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return result;
123989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
12409f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
12419f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private void readAttributeValues(
12429f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                XmlPullParser parser, String tag, Collection<String> result)
12439f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                throws XmlPullParserException, IOException {
12449f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            result.clear();
124589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            int outerDepthDAM = parser.getDepth();
12469f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            int typeDAM;
124789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            while ((typeDAM=parser.next()) != END_DOCUMENT
124889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
124989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                if (typeDAM == END_TAG || typeDAM == TEXT) {
125089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    continue;
12519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                }
12529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                String tagDAM = parser.getName();
12539f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                if (tag.equals(tagDAM)) {
12549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    result.add(parser.getAttributeValue(null, ATTR_VALUE));
12559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                } else {
12569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    Slog.e(LOG_TAG, "Expected tag " + tag +  " but found " + tagDAM);
12579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                }
12589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
12599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
12609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
12619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
12629f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1263e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten            int outerDepthDAM = parser.getDepth();
12641703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent            int typeDAM;
12659f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
12669f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            while ((typeDAM=parser.next()) != END_DOCUMENT
12679f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
12689f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                if (typeDAM == END_TAG || typeDAM == TEXT) {
12699f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    continue;
12709f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                }
127196f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten                String tagDAM = parser.getName();
1272d054c32443a493513ab63529b0c8b1aca290278cGlenn Kasten                if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1273d054c32443a493513ab63529b0c8b1aca290278cGlenn Kasten                    final String component = parser.getAttributeValue(null, ATTR_VALUE);
12749f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1275df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent                    result.put(component, trustAgentInfo);
1276df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent                } else {
1277df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
127889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                }
127989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            }
128089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            return result;
128189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
128289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
128389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
12849f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                throws XmlPullParserException, IOException  {
1285d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten            int outerDepthDAM = parser.getDepth();
1286d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten            int typeDAM;
128789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            TrustAgentInfo result = new TrustAgentInfo(null);
12889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            while ((typeDAM=parser.next()) != END_DOCUMENT
128999e53b86eebb605b70dd7591b89bf61a9414ed0eGlenn Kasten                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
129099e53b86eebb605b70dd7591b89bf61a9414ed0eGlenn Kasten                if (typeDAM == END_TAG || typeDAM == TEXT) {
1291377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT                    continue;
129289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                }
129389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                String tagDAM = parser.getName();
129489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
12959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    result.options = PersistableBundle.restoreFromXml(parser);
129689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                } else {
129789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
12989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                }
12999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
1300c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent            return result;
13019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
130289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
13039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean hasUserRestrictions() {
130489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            return userRestrictions != null && userRestrictions.size() > 0;
1305d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        }
130689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
130789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        Bundle ensureUserRestrictions() {
130889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            if (userRestrictions == null) {
130989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                userRestrictions = new Bundle();
13100ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurent            }
131189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            return userRestrictions;
13129f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
13139f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
13143302526f6276911b2dc40c731ea7fa0e7972d908Eric Laurent        void dump(String prefix, PrintWriter pw) {
131589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            pw.print(prefix); pw.print("uid="); pw.println(getUid());
13169f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            pw.print(prefix); pw.print("testOnlyAdmin=");
131789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            pw.println(testOnlyAdmin);
13189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            pw.print(prefix); pw.println("policies:");
131989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
132089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            if (pols != null) {
132189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                for (int i=0; i<pols.size(); i++) {
132289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
13239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                }
132489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            }
132589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            pw.print(prefix); pw.print("passwordQuality=0x");
132689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    pw.println(Integer.toHexString(minimumPasswordMetrics.quality));
132789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            pw.print(prefix); pw.print("minimumPasswordLength=");
132889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    pw.println(minimumPasswordMetrics.length);
132989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            pw.print(prefix); pw.print("passwordHistoryLength=");
13304ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(passwordHistoryLength);
13314ff14bae91075eb274eb1c2975982358946e7e63John Grossman            pw.print(prefix); pw.print("minimumPasswordUpperCase=");
13324ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(minimumPasswordMetrics.upperCase);
13334ff14bae91075eb274eb1c2975982358946e7e63John Grossman            pw.print(prefix); pw.print("minimumPasswordLowerCase=");
13344ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(minimumPasswordMetrics.lowerCase);
13354ff14bae91075eb274eb1c2975982358946e7e63John Grossman            pw.print(prefix); pw.print("minimumPasswordLetters=");
1336d5ed6e88a9bea1879e41d7defaf1edea7c09f554Glenn Kasten                    pw.println(minimumPasswordMetrics.letters);
13374ff14bae91075eb274eb1c2975982358946e7e63John Grossman            pw.print(prefix); pw.print("minimumPasswordNumeric=");
13384ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(minimumPasswordMetrics.numeric);
13399f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            pw.print(prefix); pw.print("minimumPasswordSymbols=");
1340d5ed6e88a9bea1879e41d7defaf1edea7c09f554Glenn Kasten                    pw.println(minimumPasswordMetrics.symbols);
1341d5ed6e88a9bea1879e41d7defaf1edea7c09f554Glenn Kasten            pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1342d5ed6e88a9bea1879e41d7defaf1edea7c09f554Glenn Kasten                    pw.println(minimumPasswordMetrics.nonLetter);
1343d5ed6e88a9bea1879e41d7defaf1edea7c09f554Glenn Kasten            pw.print(prefix); pw.print("maximumTimeToUnlock=");
13449f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    pw.println(maximumTimeToUnlock);
1345d5ed6e88a9bea1879e41d7defaf1edea7c09f554Glenn Kasten            pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
13464ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(strongAuthUnlockTimeout);
13474ff14bae91075eb274eb1c2975982358946e7e63John Grossman            pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1348c3ae93f21280859086ae371428ffd32f39e76d50Glenn Kasten                    pw.println(maximumFailedPasswordsForWipe);
1349d2c38fc4d5dc742d7441444316849510dd2b7363Glenn Kasten            pw.print(prefix); pw.print("specifiesGlobalProxy=");
135096f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten                    pw.println(specifiesGlobalProxy);
13514ff14bae91075eb274eb1c2975982358946e7e63John Grossman            pw.print(prefix); pw.print("passwordExpirationTimeout=");
13524ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(passwordExpirationTimeout);
135396f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten            pw.print(prefix); pw.print("passwordExpirationDate=");
13544ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(passwordExpirationDate);
13554ff14bae91075eb274eb1c2975982358946e7e63John Grossman            if (globalProxySpec != null) {
13564ff14bae91075eb274eb1c2975982358946e7e63John Grossman                pw.print(prefix); pw.print("globalProxySpec=");
13574ff14bae91075eb274eb1c2975982358946e7e63John Grossman                        pw.println(globalProxySpec);
13584ff14bae91075eb274eb1c2975982358946e7e63John Grossman            }
135996f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten            if (globalProxyExclusionList != null) {
13609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                pw.print(prefix); pw.print("globalProxyEclusionList=");
13614ff14bae91075eb274eb1c2975982358946e7e63John Grossman                        pw.println(globalProxyExclusionList);
13629f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
13634ff14bae91075eb274eb1c2975982358946e7e63John Grossman            pw.print(prefix); pw.print("encryptionRequested=");
1364d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten                    pw.println(encryptionRequested);
13654ff14bae91075eb274eb1c2975982358946e7e63John Grossman            pw.print(prefix); pw.print("disableCamera=");
13664ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(disableCamera);
13674ff14bae91075eb274eb1c2975982358946e7e63John Grossman            pw.print(prefix); pw.print("disableCallerId=");
13684ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(disableCallerId);
13694ff14bae91075eb274eb1c2975982358946e7e63John Grossman            pw.print(prefix); pw.print("disableContactsSearch=");
13704ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(disableContactsSearch);
13714ff14bae91075eb274eb1c2975982358946e7e63John Grossman            pw.print(prefix); pw.print("disableBluetoothContactSharing=");
13724ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(disableBluetoothContactSharing);
1373df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent            pw.print(prefix); pw.print("disableScreenCapture=");
1374df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent                    pw.println(disableScreenCapture);
1375df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent            pw.print(prefix); pw.print("requireAutoTime=");
1376d2c38fc4d5dc742d7441444316849510dd2b7363Glenn Kasten                    pw.println(requireAutoTime);
1377df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent            pw.print(prefix); pw.print("forceEphemeralUsers=");
1378df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent                    pw.println(forceEphemeralUsers);
137996f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten            pw.print(prefix); pw.print("isNetworkLoggingEnabled=");
138096f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten                    pw.println(isNetworkLoggingEnabled);
1381df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent            pw.print(prefix); pw.print("disabledKeyguardFeatures=");
13829f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    pw.println(disabledKeyguardFeatures);
1383df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent            pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1384df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent                    pw.println(crossProfileWidgetProviders);
13854ff14bae91075eb274eb1c2975982358946e7e63John Grossman            if (permittedAccessiblityServices != null) {
1386df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent                pw.print(prefix); pw.print("permittedAccessibilityServices=");
13874ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(permittedAccessiblityServices);
13884ff14bae91075eb274eb1c2975982358946e7e63John Grossman            }
13894ff14bae91075eb274eb1c2975982358946e7e63John Grossman            if (permittedInputMethods != null) {
13904ff14bae91075eb274eb1c2975982358946e7e63John Grossman                pw.print(prefix); pw.print("permittedInputMethods=");
13914ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(permittedInputMethods);
13924ff14bae91075eb274eb1c2975982358946e7e63John Grossman            }
13934ff14bae91075eb274eb1c2975982358946e7e63John Grossman            if (keepUninstalledPackages != null) {
13944ff14bae91075eb274eb1c2975982358946e7e63John Grossman                pw.print(prefix); pw.print("keepUninstalledPackages=");
13954ff14bae91075eb274eb1c2975982358946e7e63John Grossman                    pw.println(keepUninstalledPackages);
13964ff14bae91075eb274eb1c2975982358946e7e63John Grossman            }
13977c7be1e05634d96d08210efb4bdeb012ffba440dGlenn Kasten            pw.print(prefix); pw.print("organizationColor=");
139889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    pw.println(organizationColor);
1399fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten            if (organizationName != null) {
1400fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten                pw.print(prefix); pw.print("organizationName=");
1401fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten                    pw.println(organizationName);
1402fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten            }
1403fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten            pw.print(prefix); pw.println("userRestrictions:");
14041703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent            UserRestrictionsUtils.dumpRestrictions(pw, prefix + "  ", userRestrictions);
1405a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten            pw.print(prefix); pw.print("defaultEnabledRestrictionsAlreadySet=");
1406a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten                    pw.println(defaultEnabledRestrictionsAlreadySet);
1407a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten            pw.print(prefix); pw.print("isParent=");
1408a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten                    pw.println(isParent);
1409a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten            if (parentAdmin != null) {
1410a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten                pw.print(prefix);  pw.println("parentAdmin:");
1411a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten                parentAdmin.dump(prefix + "  ", pw);
1412a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten            }
1413a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        }
1414a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten    }
1415a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten
1416a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten    private void handlePackagesChanged(String packageName, int userHandle) {
1417a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        boolean removedAdmin = false;
1418a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1419a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        DevicePolicyData policy = getUserData(userHandle);
1420a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        synchronized (this) {
1421a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten            for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1422b0dfd4613225a3b2a17bdf8d85e89a4b04d65ef3Glenn Kasten                ActiveAdmin aa = policy.mAdminList.get(i);
1423b0dfd4613225a3b2a17bdf8d85e89a4b04d65ef3Glenn Kasten                try {
1424a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten                    // If we're checking all packages or if the specific one we're checking matches,
14251703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent                    // then check if the package and receiver still exist.
14269f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    final String adminPackage = aa.info.getPackageName();
14279f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    if (packageName == null || packageName.equals(adminPackage)) {
142896f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten                        if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1429a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten                                || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
14309f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                                        PackageManager.MATCH_DIRECT_BOOT_AWARE
14319f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1432b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                                        userHandle) == null) {
1433b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                            removedAdmin = true;
1434b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                            policy.mAdminList.remove(i);
143523a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten                            policy.mAdminMap.remove(aa.info.getComponent());
1436b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                        }
1437b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    }
1438b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                } catch (RemoteException re) {
1439b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    // Shouldn't happen.
1440b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                }
144189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            }
1442c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent            if (removedAdmin) {
1443b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                validatePasswordOwnerLocked(policy);
14449f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
144589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
14469f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            boolean removedDelegate = false;
14479f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
14489f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // Check if a delegate was removed.
14499f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
14509f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                final String delegatePackage = policy.mDelegationMap.keyAt(i);
14519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
14529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    policy.mDelegationMap.removeAt(i);
14539f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    removedDelegate = true;
14549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                }
14559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
14569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
14579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // Persist updates if the removed package was an admin or delegate.
14589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            if (removedAdmin || removedDelegate) {
14599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                saveSettingsLocked(policy.mUserHandle);
14609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
14619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
14629f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (removedAdmin) {
14639f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // The removed admin might have disabled camera, so update user restrictions.
146489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            pushUserRestrictions(userHandle);
146589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
14669f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
14679f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
14689f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
146989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        try {
14709f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return targetPackage != null
14719f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    && (changedPackage == null || changedPackage.equals(targetPackage))
14729f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
14739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        } catch (RemoteException e) {
14749f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // Shouldn't happen
14759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
14769f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
14779f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return false;
14789f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
14799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
14809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    /**
14819f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten     * Unit test will subclass it to inject mocks.
14829f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten     */
14839f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    @VisibleForTesting
14849f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    static class Injector {
14859f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
14869f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        private final Context mContext;
14879f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
14889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        Injector(Context context) {
14899f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            mContext = context;
14909f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
14919f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
14929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        Owners newOwners() {
14939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return new Owners(getUserManager(), getUserManagerInternal(),
14949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    getPackageManagerInternal());
14959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
14969f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
1497b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        UserManager getUserManager() {
14989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return UserManager.get(mContext);
14999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
15009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        UserManagerInternal getUserManagerInternal() {
15029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return LocalServices.getService(UserManagerInternal.class);
15039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
15049f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
1505b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        PackageManagerInternal getPackageManagerInternal() {
1506b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            return LocalServices.getService(PackageManagerInternal.class);
1507b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
1508b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
1509b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        NotificationManager getNotificationManager() {
1510b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            return mContext.getSystemService(NotificationManager.class);
1511b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
1512b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
1513b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        IIpConnectivityMetrics getIIpConnectivityMetrics() {
1514b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1515b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1516b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
1517b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
1518b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        PackageManager getPackageManager() {
1519b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            return mContext.getPackageManager();
1520b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
1521b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
1522b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        PowerManagerInternal getPowerManagerInternal() {
1523b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            return LocalServices.getService(PowerManagerInternal.class);
1524b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
1525b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
1526b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        TelephonyManager getTelephonyManager() {
1527b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            return TelephonyManager.from(mContext);
1528b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
1529b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
1530b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        TrustManager getTrustManager() {
1531b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1532b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
1533b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
1534b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        IWindowManager getIWindowManager() {
1535b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            return IWindowManager.Stub
1536b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
15379f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
15389f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15399f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        IActivityManager getIActivityManager() {
15409f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return ActivityManager.getService();
15419f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
15429f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15439f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        IPackageManager getIPackageManager() {
15449f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return AppGlobals.getPackageManager();
15459f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
15469f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15479f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        IBackupManager getIBackupManager() {
15489f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return IBackupManager.Stub.asInterface(
15499f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    ServiceManager.getService(Context.BACKUP_SERVICE));
15509f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
15519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        IAudioService getIAudioService() {
15539f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
15549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
15559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean isBuildDebuggable() {
15579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return Build.IS_DEBUGGABLE;
1558b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
15599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        LockPatternUtils newLockPatternUtils() {
15619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return new LockPatternUtils(mContext);
1562b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
1563b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
1564b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        boolean storageManagerIsFileBasedEncryptionEnabled() {
1565b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            return StorageManager.isFileEncryptedNativeOnly();
156689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
156789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
15689f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean storageManagerIsNonDefaultBlockEncrypted() {
15699f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            long identity = Binder.clearCallingIdentity();
15709f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            try {
157189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                return StorageManager.isNonDefaultBlockEncrypted();
157289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            } finally {
15739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                Binder.restoreCallingIdentity(identity);
15749f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
15759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
15769f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15779f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean storageManagerIsEncrypted() {
15789f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return StorageManager.isEncrypted();
15799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
15809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15819f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean storageManagerIsEncryptable() {
15829f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return StorageManager.isEncryptable();
15839f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
158489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
158589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        Looper getMyLooper() {
15869f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return Looper.myLooper();
15879f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
15889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15899f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        WifiManager getWifiManager() {
15902267ba18d0d2b2d4bd7f5411821ad89ac2659a88Eric Laurent            return mContext.getSystemService(WifiManager.class);
15912267ba18d0d2b2d4bd7f5411821ad89ac2659a88Eric Laurent        }
15929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        long binderClearCallingIdentity() {
15949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return Binder.clearCallingIdentity();
15959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
15969f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15979f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        void binderRestoreCallingIdentity(long token) {
15989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            Binder.restoreCallingIdentity(token);
15999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        int binderGetCallingUid() {
16029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return Binder.getCallingUid();
16039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
160489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
16059f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        int binderGetCallingPid() {
16069f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return Binder.getCallingPid();
16079f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16089f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16099f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        UserHandle binderGetCallingUserHandle() {
16109f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return Binder.getCallingUserHandle();
16119f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16129f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16139f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean binderIsCallingUidMyUid() {
16149f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return getCallingUid() == Process.myUid();
1615c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent        }
16169f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16179f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        final int userHandleGetCallingUserId() {
16189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return UserHandle.getUserId(binderGetCallingUid());
16199f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16209f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16219f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        File environmentGetUserSystemDirectory(int userId) {
16229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return Environment.getUserSystemDirectory(userId);
16239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
1624b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
1625b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        void powerManagerGoToSleep(long time, int reason, int flags) {
16269f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1627b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
1628b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
16299f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        void powerManagerReboot(String reason) {
163089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            mContext.getSystemService(PowerManager.class).reboot(reason);
16319f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16329f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
163389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force)
16349f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                throws IOException {
163542a6f422c09ca6a960673e0e805ddf71a9b51befEric Laurent            RecoverySystem.rebootWipeUserData(mContext, shutdown, reason, force);
16369f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16379f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16389f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean systemPropertiesGetBoolean(String key, boolean def) {
16399f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return SystemProperties.getBoolean(key, def);
16409f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16419f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16429f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        long systemPropertiesGetLong(String key, long def) {
16439f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return SystemProperties.getLong(key, def);
1644d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        }
164589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
164689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        String systemPropertiesGet(String key, String def) {
164789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            return SystemProperties.get(key, def);
164889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
16490ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurent
165089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        String systemPropertiesGet(String key) {
165189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            return SystemProperties.get(key);
165289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
165389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
165489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        void systemPropertiesSet(String key, String value) {
16559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            SystemProperties.set(key, value);
165689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
165789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
16589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        boolean userManagerIsSplitSystemUser() {
16599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return UserManager.isSplitSystemUser();
16609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16629f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        String getDevicePolicyFilePathForSystemUser() {
16639f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return "/data/system/";
16649f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16658555d0867c3e8fe6cc5c7ad40af557fe6b92fa72The Android Open Source Project
16668555d0867c3e8fe6cc5c7ad40af557fe6b92fa72The Android Open Source Project        void registerContentObserver(Uri uri, boolean notifyForDescendents,
16678555d0867c3e8fe6cc5c7ad40af557fe6b92fa72The Android Open Source Project                ContentObserver observer, int userHandle) {
16688555d0867c3e8fe6cc5c7ad40af557fe6b92fa72The Android Open Source Project            mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
16699f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    observer, userHandle);
1670d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        }
167189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
16720ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurent        int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1673511754b5839fd9b09fc56b89ae007fbc39084a33Glenn Kasten            return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1674511754b5839fd9b09fc56b89ae007fbc39084a33Glenn Kasten                    name, def, userHandle);
16759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
167689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
167789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        void settingsSecurePutIntForUser(String name, int value, int userHandle) {
16789f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            Settings.Secure.putIntForUser(mContext.getContentResolver(),
16799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    name, value, userHandle);
16809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16819f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16829f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        void settingsSecurePutStringForUser(String name, String value, int userHandle) {
16839f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            Settings.Secure.putStringForUser(mContext.getContentResolver(),
16849f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    name, value, userHandle);
16859f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
168689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
168789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
168889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            Settings.Global.putStringForUser(mContext.getContentResolver(),
16899f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    name, value, userHandle);
16909f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16919f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        void settingsSecurePutInt(String name, int value) {
16939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            Settings.Secure.putInt(mContext.getContentResolver(), name, value);
16949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16969f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        int settingsGlobalGetInt(String name, int def) {
16979f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return Settings.Global.getInt(mContext.getContentResolver(), name, def);
16989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
16999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
17009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        void settingsGlobalPutInt(String name, int value) {
17019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            Settings.Global.putInt(mContext.getContentResolver(), name, value);
17029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
17039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
17049f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        void settingsSecurePutString(String name, String value) {
17059f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            Settings.Secure.putString(mContext.getContentResolver(), name, value);
17069f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
17079f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
17089f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        void settingsGlobalPutString(String name, String value) {
17099f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            Settings.Global.putString(mContext.getContentResolver(), name, value);
171089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
17119f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
17129f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        void securityLogSetLoggingEnabledProperty(boolean enabled) {
17139f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            SecurityLog.setLoggingEnabledProperty(enabled);
17149f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
17159f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
171689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        boolean securityLogGetLoggingEnabledProperty() {
171789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            return SecurityLog.getLoggingEnabledProperty();
17189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
17191703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent
1720b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        boolean securityLogIsLoggingEnabled() {
172123a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten            return SecurityLog.isLoggingEnabled();
17229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
17231703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    }
17241703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent
1725a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten    /**
172638e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten     * Instantiates the service.
1727a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten     */
1728a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten    public DevicePolicyManagerService(Context context) {
172923a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten        this(new Injector(context));
173023a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten    }
1731b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
1732b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    @VisibleForTesting
1733b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    DevicePolicyManagerService(Injector injector) {
1734a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten        mInjector = injector;
1735a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten        mContext = Preconditions.checkNotNull(injector.mContext);
1736a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten        mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1737cc21e4f1e41dfa17e7e2bef995fcd22c45f6bcd0Eric Laurent        mOwners = Preconditions.checkNotNull(injector.newOwners());
1738cc21e4f1e41dfa17e7e2bef995fcd22c45f6bcd0Eric Laurent
1739cc21e4f1e41dfa17e7e2bef995fcd22c45f6bcd0Eric Laurent        mUserManager = Preconditions.checkNotNull(injector.getUserManager());
17409f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1741363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten        mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1742a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten        mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1743a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten
17449f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mLocalService = new LocalService();
17459f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mLockPatternUtils = injector.newLockPatternUtils();
17469f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
17479f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mSecurityLogMonitor = new SecurityLogMonitor(this);
17489f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
17499f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mHasFeature = mInjector.getPackageManager()
17509f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
17519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mIsWatch = mInjector.getPackageManager()
17529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                .hasSystemFeature(PackageManager.FEATURE_WATCH);
17539f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (!mHasFeature) {
1754a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten            // Skip the rest of the initialization
17559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return;
1756a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten        }
1757a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten        IntentFilter filter = new IntentFilter();
1758a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten        filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1759a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten        filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
176096f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten        filter.addAction(Intent.ACTION_USER_ADDED);
17611703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent        filter.addAction(Intent.ACTION_USER_REMOVED);
17621703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent        filter.addAction(Intent.ACTION_USER_STARTED);
17639f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        filter.addAction(Intent.ACTION_USER_UNLOCKED);
17649f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        filter.addAction(KeyChain.ACTION_TRUST_STORE_CHANGED);
1765a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
17661703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
17671703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent        filter = new IntentFilter();
17689f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
17692b2165c75790050810460c8de3f414876bce4c0eGlenn Kasten        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
177038e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
177138e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1772b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        filter.addDataScheme("package");
1773b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
177438e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        filter = new IntentFilter();
177538e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
177638e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
177738e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten
177838e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
17799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
17809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
17811703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    /**
17821703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent     * Creates and loads the policy data from xml.
17831703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent     * @param userHandle the user for whom to load the policy data
17841703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent     * @return
17851703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent     */
1786ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald    @NonNull
1787ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald    DevicePolicyData getUserData(int userHandle) {
1788ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald        synchronized (this) {
178953cec22821072719ee02c856e9ac2dda2496c570Glenn Kasten            DevicePolicyData policy = mUserData.get(userHandle);
1790ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald            if (policy == null) {
1791ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald                policy = new DevicePolicyData(userHandle);
1792ce70374bf105f8a6160bf5dd70affea012b2a464Glenn Kasten                mUserData.append(userHandle, policy);
1793ce70374bf105f8a6160bf5dd70affea012b2a464Glenn Kasten                loadSettingsLocked(policy, userHandle);
179453cec22821072719ee02c856e9ac2dda2496c570Glenn Kasten            }
1795fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten            return policy;
1796fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten        }
1797fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten    }
1798fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten
1799fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten    /**
1800fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten     * Creates and loads the policy data from xml for data that is shared between
1801fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten     * various profiles of a user. In contrast to {@link #getUserData(int)}
1802fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten     * it allows access to data of users other than the calling user.
1803fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten     *
1804fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten     * This function should only be used for shared data, e.g. everything regarding
1805fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten     * passwords and should be removed once multiple screen locks are present.
1806fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten     * @param userHandle the user for whom to load the policy data
1807ce70374bf105f8a6160bf5dd70affea012b2a464Glenn Kasten     * @return
1808ce70374bf105f8a6160bf5dd70affea012b2a464Glenn Kasten     */
1809ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald    DevicePolicyData getUserDataUnchecked(int userHandle) {
1810ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald        long ident = mInjector.binderClearCallingIdentity();
18112c6c5294388e251ebc1e00d6c8785190561c27fcGlenn Kasten        try {
18122c6c5294388e251ebc1e00d6c8785190561c27fcGlenn Kasten            return getUserData(userHandle);
18132c6c5294388e251ebc1e00d6c8785190561c27fcGlenn Kasten        } finally {
1814b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            mInjector.binderRestoreCallingIdentity(ident);
1815b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
1816b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    }
1817ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald
1818ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald    void removeUserData(int userHandle) {
181923a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten        synchronized (this) {
182023a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten            if (userHandle == UserHandle.USER_SYSTEM) {
182123a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten                Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
182223a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten                return;
182323a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten            }
182423a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten            mOwners.removeProfileOwner(userHandle);
18257c7be1e05634d96d08210efb4bdeb012ffba440dGlenn Kasten            mOwners.writeProfileOwner(userHandle);
182689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
182789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            DevicePolicyData policy = mUserData.get(userHandle);
182889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            if (policy != null) {
182989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                mUserData.remove(userHandle);
183089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            }
183189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
183289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    DEVICE_POLICIES_XML);
183385ab62c4b433df3f1a9826bed1c9bec07a86c750Glenn Kasten            policyFile.delete();
183485ab62c4b433df3f1a9826bed1c9bec07a86c750Glenn Kasten            Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
183589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
1836377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT        updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1837b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten    }
183889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1839e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    void loadOwners() {
184089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        synchronized (this) {
18419f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            mOwners.load();
184289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            setDeviceOwnerSystemPropertyLocked();
184389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            findOwnerComponentIfNecessaryLocked();
184489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            migrateUserRestrictionsIfNecessaryLocked();
184589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            setDefaultEnabledUserRestrictionsIfNecessaryLocked();
184689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
18479f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // TODO PO may not have a class name either due to b/17652534.  Address that too.
18489f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
18499f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            updateDeviceOwnerLocked();
18509f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
18519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
18529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
18539f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private void setDefaultEnabledUserRestrictionsIfNecessaryLocked() {
18549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
18557c7be1e05634d96d08210efb4bdeb012ffba440dGlenn Kasten        if (deviceOwner != null
18569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                && !UserRestrictionsUtils.getDefaultEnabledForDeviceOwner().equals(
18579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                        deviceOwner.defaultEnabledRestrictionsAlreadySet)) {
18589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            Slog.i(LOG_TAG,"New user restrictions need to be set by default for the device owner");
18599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
18609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            if (VERBOSE_LOG) {
18619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                Slog.d(LOG_TAG,"Default enabled restrictions for DO: "
18629f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                        + UserRestrictionsUtils.getDefaultEnabledForDeviceOwner()
18639f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                        + ". Restrictions already enabled: "
186489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                        + deviceOwner.defaultEnabledRestrictionsAlreadySet);
186589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            }
186689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1867598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten            Set<String> restrictionsToSet = new ArraySet<>(
1868598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten                    UserRestrictionsUtils.getDefaultEnabledForDeviceOwner());
18693acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            restrictionsToSet.removeAll(deviceOwner.defaultEnabledRestrictionsAlreadySet);
18703acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            if (!restrictionsToSet.isEmpty()) {
18713acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                for (String restriction : restrictionsToSet) {
18723acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                    deviceOwner.ensureUserRestrictions().putBoolean(restriction, true);
187389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                }
187489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                deviceOwner.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet);
187589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                Slog.i(LOG_TAG,
187689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                        "Enabled the following restrictions by default: " + restrictionsToSet);
187789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
18783acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                saveUserRestrictionsLocked(mOwners.getDeviceOwnerUserId());
18793acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            }
18803acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        }
18813acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    }
18823acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten
18833acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    private void setDeviceOwnerSystemPropertyLocked() {
18843acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        // Device owner may still be provisioned, do not set the read-only system property yet.
1885598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten        if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1886598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten            return;
1887598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten        }
1888598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten        // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
18895a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        // always false at this point.
18905a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        if (StorageManager.inCryptKeeperBounce()) {
18915a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten            return;
18925a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        }
18935a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten
18945a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
18959d2c78c4798ffd8c276c1bf0eaa0b34bc255a2daEric Laurent            Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
18965a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        } else {
18975a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten            if (mOwners.hasDeviceOwner()) {
18983acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
18997c7be1e05634d96d08210efb4bdeb012ffba440dGlenn Kasten                Slog.i(LOG_TAG, "Set ro.device_owner property to true");
19009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
19019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                if (mInjector.securityLogGetLoggingEnabledProperty()) {
19029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    mSecurityLogMonitor.start();
19039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    maybePauseDeviceWideLoggingLocked();
19045a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten                }
19059f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            } else {
19069f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
19079f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                Slog.i(LOG_TAG, "Set ro.device_owner property to false");
19085a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten            }
19095a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        }
19105a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten    }
19115a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten
19129f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    private void findOwnerComponentIfNecessaryLocked() {
19139f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (!mOwners.hasDeviceOwner()) {
19145a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten            return;
19159f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
1916ca8b28013c0558a4a3323a1a0f58520277200086Glenn Kasten        final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
191789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
191889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        if (!TextUtils.isEmpty(doComponentName.getClassName())) {
19193acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            return; // Already a full component name.
19203acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        }
19213acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten
19223acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        final ComponentName doComponent = findAdminComponentWithPackageLocked(
1923598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten                doComponentName.getPackageName(),
19243acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                mOwners.getDeviceOwnerUserId());
19253acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        if (doComponent == null) {
19263acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
19273acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        } else {
19283acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            mOwners.setDeviceOwnerWithRestrictionsMigrated(
19293acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                    doComponent,
19303acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                    mOwners.getDeviceOwnerName(),
19313acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                    mOwners.getDeviceOwnerUserId(),
19323acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                    !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
19333acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            mOwners.writeDeviceOwner();
19343acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            if (VERBOSE_LOG) {
1935598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten                Log.v(LOG_TAG, "Device owner component filled in");
19369d2c78c4798ffd8c276c1bf0eaa0b34bc255a2daEric Laurent            }
19373acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        }
19389d2c78c4798ffd8c276c1bf0eaa0b34bc255a2daEric Laurent    }
19393acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten
19403acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    /**
19413acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten     * We didn't use to persist user restrictions for each owners but only persisted in user
19423acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten     * manager.
19435a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten     */
19445a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten    private void migrateUserRestrictionsIfNecessaryLocked() {
19455a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        boolean migrated = false;
19465a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        // Migrate for the DO.  Basically all restrictions should be considered to be set by DO,
19475a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        // except for the "system controlled" ones.
19485a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
19495a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten            if (VERBOSE_LOG) {
195089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                Log.v(LOG_TAG, "Migrating DO user restrictions");
1951            }
1952            migrated = true;
1953
1954            // Migrate user 0 restrictions to DO.
1955            final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1956
1957            migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1958                    /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1959
1960            // Push DO user restrictions to user manager.
1961            pushUserRestrictions(UserHandle.USER_SYSTEM);
1962
1963            mOwners.setDeviceOwnerUserRestrictionsMigrated();
1964        }
1965
1966        // Migrate for POs.
1967
1968        // The following restrictions can be set on secondary users by the device owner, so we
1969        // assume they're not from the PO.
1970        final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1971                UserManager.DISALLOW_OUTGOING_CALLS,
1972                UserManager.DISALLOW_SMS);
1973
1974        for (UserInfo ui : mUserManager.getUsers()) {
1975            final int userId = ui.id;
1976            if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1977                if (VERBOSE_LOG) {
1978                    Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1979                }
1980                migrated = true;
1981
1982                final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1983
1984                final Set<String> exceptionList =
1985                        (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1986
1987                migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1988                        exceptionList, /* isDeviceOwner =*/ false);
1989
1990                // Note if a secondary user has no PO but has a DA that disables camera, we
1991                // don't get here and won't push the camera user restriction to UserManager
1992                // here.  That's okay because we'll push user restrictions anyway when a user
1993                // starts.  But we still do it because we want to let user manager persist
1994                // upon migration.
1995                pushUserRestrictions(userId);
1996
1997                mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1998            }
1999        }
2000        if (VERBOSE_LOG && migrated) {
2001            Log.v(LOG_TAG, "User restrictions migrated.");
2002        }
2003    }
2004
2005    private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
2006            Set<String> exceptionList, boolean isDeviceOwner) {
2007        final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
2008                user.getIdentifier());
2009
2010        final Bundle newBaseRestrictions = new Bundle();
2011        final Bundle newOwnerRestrictions = new Bundle();
2012
2013        for (String key : origRestrictions.keySet()) {
2014            if (!origRestrictions.getBoolean(key)) {
2015                continue;
2016            }
2017            final boolean canOwnerChange = isDeviceOwner
2018                    ? UserRestrictionsUtils.canDeviceOwnerChange(key)
2019                    : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
2020
2021            if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
2022                newBaseRestrictions.putBoolean(key, true);
2023            } else {
2024                newOwnerRestrictions.putBoolean(key, true);
2025            }
2026        }
2027
2028        if (VERBOSE_LOG) {
2029            Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
2030            Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
2031            Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
2032        }
2033        mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
2034                newBaseRestrictions);
2035
2036        if (admin != null) {
2037            admin.ensureUserRestrictions().clear();
2038            admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
2039        } else {
2040            Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
2041        }
2042        saveSettingsLocked(user.getIdentifier());
2043    }
2044
2045    private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
2046        final DevicePolicyData policy = getUserData(userId);
2047        final int n = policy.mAdminList.size();
2048        ComponentName found = null;
2049        int nFound = 0;
2050        for (int i = 0; i < n; i++) {
2051            final ActiveAdmin admin = policy.mAdminList.get(i);
2052            if (packageName.equals(admin.info.getPackageName())) {
2053                // Found!
2054                if (nFound == 0) {
2055                    found = admin.info.getComponent();
2056                }
2057                nFound++;
2058            }
2059        }
2060        if (nFound > 1) {
2061            Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
2062        }
2063        return found;
2064    }
2065
2066    /**
2067     * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
2068     * reminders.  Clears alarm if no expirations are configured.
2069     */
2070    private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
2071        final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
2072        final long now = System.currentTimeMillis();
2073        final long timeToExpire = expiration - now;
2074        final long alarmTime;
2075        if (expiration == 0) {
2076            // No expirations are currently configured:  Cancel alarm.
2077            alarmTime = 0;
2078        } else if (timeToExpire <= 0) {
2079            // The password has already expired:  Repeat every 24 hours.
2080            alarmTime = now + MS_PER_DAY;
2081        } else {
2082            // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
2083            // the expiration time.
2084            long alarmInterval = timeToExpire % MS_PER_DAY;
2085            if (alarmInterval == 0) {
2086                alarmInterval = MS_PER_DAY;
2087            }
2088            alarmTime = now + alarmInterval;
2089        }
2090
2091        long token = mInjector.binderClearCallingIdentity();
2092        try {
2093            int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
2094            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
2095            PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2096                    new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2097                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
2098                    UserHandle.of(affectedUserHandle));
2099            am.cancel(pi);
2100            if (alarmTime != 0) {
2101                am.set(AlarmManager.RTC, alarmTime, pi);
2102            }
2103        } finally {
2104            mInjector.binderRestoreCallingIdentity(token);
2105        }
2106    }
2107
2108    ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2109        ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2110        if (admin != null
2111                && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2112                && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2113            return admin;
2114        }
2115        return null;
2116    }
2117
2118    ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2119        if (parent) {
2120            enforceManagedProfile(userHandle, "call APIs on the parent profile");
2121        }
2122        ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2123        if (admin != null && parent) {
2124            admin = admin.getParentActiveAdmin();
2125        }
2126        return admin;
2127    }
2128
2129    ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2130            throws SecurityException {
2131        final int callingUid = mInjector.binderGetCallingUid();
2132
2133        ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
2134        if (result != null) {
2135            return result;
2136        }
2137
2138        if (who != null) {
2139            final int userId = UserHandle.getUserId(callingUid);
2140            final DevicePolicyData policy = getUserData(userId);
2141            ActiveAdmin admin = policy.mAdminMap.get(who);
2142            if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2143                throw new SecurityException("Admin " + admin.info.getComponent()
2144                         + " does not own the device");
2145            }
2146            if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2147                throw new SecurityException("Admin " + admin.info.getComponent()
2148                        + " does not own the profile");
2149            }
2150            throw new SecurityException("Admin " + admin.info.getComponent()
2151                    + " did not specify uses-policy for: "
2152                    + admin.info.getTagForPolicy(reqPolicy));
2153        } else {
2154            throw new SecurityException("No active admin owned by uid "
2155                    + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
2156        }
2157    }
2158
2159    ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2160            throws SecurityException {
2161        if (parent) {
2162            enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2163                    "call APIs on the parent profile");
2164        }
2165        ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2166        return parent ? admin.getParentActiveAdmin() : admin;
2167    }
2168    /**
2169     * Find the admin for the component and userId bit of the uid, then check
2170     * the admin's uid matches the uid.
2171     */
2172    private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2173        final int userId = UserHandle.getUserId(uid);
2174        final DevicePolicyData policy = getUserData(userId);
2175        ActiveAdmin admin = policy.mAdminMap.get(who);
2176        if (admin == null) {
2177            throw new SecurityException("No active admin " + who);
2178        }
2179        if (admin.getUid() != uid) {
2180            throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2181        }
2182        return admin;
2183    }
2184
2185    private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2186            int uid) {
2187        // Try to find an admin which can use reqPolicy
2188        final int userId = UserHandle.getUserId(uid);
2189        final DevicePolicyData policy = getUserData(userId);
2190        if (who != null) {
2191            ActiveAdmin admin = policy.mAdminMap.get(who);
2192            if (admin == null) {
2193                throw new SecurityException("No active admin " + who);
2194            }
2195            if (admin.getUid() != uid) {
2196                throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2197            }
2198            if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2199                return admin;
2200            }
2201        } else {
2202            for (ActiveAdmin admin : policy.mAdminList) {
2203                if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2204                        userId)) {
2205                    return admin;
2206                }
2207            }
2208        }
2209
2210        return null;
2211    }
2212
2213    @VisibleForTesting
2214    boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2215            int userId) {
2216        final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2217        final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2218
2219        if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2220            return ownsDevice;
2221        } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2222            // DO always has the PO power.
2223            return ownsDevice || ownsProfile;
2224        } else {
2225            return admin.info.usesPolicy(reqPolicy);
2226        }
2227    }
2228
2229    void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2230        sendAdminCommandLocked(admin, action, null);
2231    }
2232
2233    void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2234        sendAdminCommandLocked(admin, action, null, result);
2235    }
2236
2237    /**
2238     * Send an update to one specific admin, get notified when that admin returns a result.
2239     */
2240    void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2241            BroadcastReceiver result) {
2242        Intent intent = new Intent(action);
2243        intent.setComponent(admin.info.getComponent());
2244        if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2245            intent.putExtra("expiration", admin.passwordExpirationDate);
2246        }
2247        if (adminExtras != null) {
2248            intent.putExtras(adminExtras);
2249        }
2250        if (result != null) {
2251            mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2252                    null, result, mHandler, Activity.RESULT_OK, null, null);
2253        } else {
2254            mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2255        }
2256    }
2257
2258    /**
2259     * Send an update to all admins of a user that enforce a specified policy.
2260     */
2261    void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) {
2262        final DevicePolicyData policy = getUserData(userHandle);
2263        final int count = policy.mAdminList.size();
2264        for (int i = 0; i < count; i++) {
2265            final ActiveAdmin admin = policy.mAdminList.get(i);
2266            if (admin.info.usesPolicy(reqPolicy)) {
2267                sendAdminCommandLocked(admin, action, adminExtras, null);
2268            }
2269        }
2270    }
2271
2272    /**
2273     * Send an update intent to all admins of a user and its profiles. Only send to admins that
2274     * enforce a specified policy.
2275     */
2276    private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2277            int userHandle, Bundle adminExtras) {
2278        int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2279        for (int profileId : profileIds) {
2280            sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras);
2281        }
2282    }
2283
2284    /**
2285     * Sends a broadcast to each profile that share the password unlock with the given user id.
2286     */
2287    private void sendAdminCommandForLockscreenPoliciesLocked(
2288            String action, int reqPolicy, int userHandle) {
2289        final Bundle extras = new Bundle();
2290        extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
2291        if (isSeparateProfileChallengeEnabled(userHandle)) {
2292            sendAdminCommandLocked(action, reqPolicy, userHandle, extras);
2293        } else {
2294            sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras);
2295        }
2296    }
2297
2298    void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2299        final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2300        DevicePolicyData policy = getUserData(userHandle);
2301        if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2302            policy.mRemovingAdmins.add(adminReceiver);
2303            sendAdminCommandLocked(admin,
2304                    DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2305                    new BroadcastReceiver() {
2306                        @Override
2307                        public void onReceive(Context context, Intent intent) {
2308                            removeAdminArtifacts(adminReceiver, userHandle);
2309                            removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2310                        }
2311                    });
2312        }
2313    }
2314
2315
2316    public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2317            boolean throwForMissiongPermission) {
2318        if (!mHasFeature) {
2319            return null;
2320        }
2321        enforceFullCrossUsersPermission(userHandle);
2322        ActivityInfo ai = null;
2323        try {
2324            ai = mIPackageManager.getReceiverInfo(adminName,
2325                    PackageManager.GET_META_DATA |
2326                    PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2327                    PackageManager.MATCH_DIRECT_BOOT_AWARE |
2328                    PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2329        } catch (RemoteException e) {
2330            // shouldn't happen.
2331        }
2332        if (ai == null) {
2333            throw new IllegalArgumentException("Unknown admin: " + adminName);
2334        }
2335
2336        if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2337            final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2338                    + permission.BIND_DEVICE_ADMIN;
2339            Slog.w(LOG_TAG, message);
2340            if (throwForMissiongPermission &&
2341                    ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2342                throw new IllegalArgumentException(message);
2343            }
2344        }
2345
2346        try {
2347            return new DeviceAdminInfo(mContext, ai);
2348        } catch (XmlPullParserException | IOException e) {
2349            Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2350                    e);
2351            return null;
2352        }
2353    }
2354
2355    private JournaledFile makeJournaledFile(int userHandle) {
2356        final String base = userHandle == UserHandle.USER_SYSTEM
2357                ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2358                : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2359                        DEVICE_POLICIES_XML).getAbsolutePath();
2360        if (VERBOSE_LOG) {
2361            Log.v(LOG_TAG, "Opening " + base);
2362        }
2363        return new JournaledFile(new File(base), new File(base + ".tmp"));
2364    }
2365
2366    private void saveSettingsLocked(int userHandle) {
2367        DevicePolicyData policy = getUserData(userHandle);
2368        JournaledFile journal = makeJournaledFile(userHandle);
2369        FileOutputStream stream = null;
2370        try {
2371            stream = new FileOutputStream(journal.chooseForWrite(), false);
2372            XmlSerializer out = new FastXmlSerializer();
2373            out.setOutput(stream, StandardCharsets.UTF_8.name());
2374            out.startDocument(null, true);
2375
2376            out.startTag(null, "policies");
2377            if (policy.mRestrictionsProvider != null) {
2378                out.attribute(null, ATTR_PERMISSION_PROVIDER,
2379                        policy.mRestrictionsProvider.flattenToString());
2380            }
2381            if (policy.mUserSetupComplete) {
2382                out.attribute(null, ATTR_SETUP_COMPLETE,
2383                        Boolean.toString(true));
2384            }
2385            if (policy.mPaired) {
2386                out.attribute(null, ATTR_DEVICE_PAIRED,
2387                        Boolean.toString(true));
2388            }
2389            if (policy.mDeviceProvisioningConfigApplied) {
2390                out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2391                        Boolean.toString(true));
2392            }
2393            if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2394                out.attribute(null, ATTR_PROVISIONING_STATE,
2395                        Integer.toString(policy.mUserProvisioningState));
2396            }
2397            if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2398                out.attribute(null, ATTR_PERMISSION_POLICY,
2399                        Integer.toString(policy.mPermissionPolicy));
2400            }
2401
2402            // Serialize delegations.
2403            for (int i = 0; i < policy.mDelegationMap.size(); ++i) {
2404                final String delegatePackage = policy.mDelegationMap.keyAt(i);
2405                final List<String> scopes = policy.mDelegationMap.valueAt(i);
2406
2407                // Every "delegation" tag serializes the information of one delegate-scope pair.
2408                for (String scope : scopes) {
2409                    out.startTag(null, "delegation");
2410                    out.attribute(null, "delegatePackage", delegatePackage);
2411                    out.attribute(null, "scope", scope);
2412                    out.endTag(null, "delegation");
2413                }
2414            }
2415
2416            final int N = policy.mAdminList.size();
2417            for (int i=0; i<N; i++) {
2418                ActiveAdmin ap = policy.mAdminList.get(i);
2419                if (ap != null) {
2420                    out.startTag(null, "admin");
2421                    out.attribute(null, "name", ap.info.getComponent().flattenToString());
2422                    ap.writeToXml(out);
2423                    out.endTag(null, "admin");
2424                }
2425            }
2426
2427            if (policy.mPasswordOwner >= 0) {
2428                out.startTag(null, "password-owner");
2429                out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2430                out.endTag(null, "password-owner");
2431            }
2432
2433            if (policy.mFailedPasswordAttempts != 0) {
2434                out.startTag(null, "failed-password-attempts");
2435                out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2436                out.endTag(null, "failed-password-attempts");
2437            }
2438
2439            // Don't save metrics for FBE devices
2440            final PasswordMetrics metrics = policy.mActivePasswordMetrics;
2441            if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && !metrics.isDefault()) {
2442                out.startTag(null, "active-password");
2443                out.attribute(null, "quality", Integer.toString(metrics.quality));
2444                out.attribute(null, "length", Integer.toString(metrics.length));
2445                out.attribute(null, "uppercase", Integer.toString(metrics.upperCase));
2446                out.attribute(null, "lowercase", Integer.toString(metrics.lowerCase));
2447                out.attribute(null, "letters", Integer.toString(metrics.letters));
2448                out.attribute(null, "numeric", Integer.toString(metrics.numeric));
2449                out.attribute(null, "symbols", Integer.toString(metrics.symbols));
2450                out.attribute(null, "nonletter", Integer.toString(metrics.nonLetter));
2451                out.endTag(null, "active-password");
2452            }
2453
2454            for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2455                out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2456                out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2457                out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2458            }
2459
2460            for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2461                String component = policy.mLockTaskPackages.get(i);
2462                out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2463                out.attribute(null, "name", component);
2464                out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2465            }
2466
2467            if (policy.mStatusBarDisabled) {
2468                out.startTag(null, TAG_STATUS_BAR);
2469                out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2470                out.endTag(null, TAG_STATUS_BAR);
2471            }
2472
2473            if (policy.doNotAskCredentialsOnBoot) {
2474                out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2475                out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2476            }
2477
2478            for (String id : policy.mAffiliationIds) {
2479                out.startTag(null, TAG_AFFILIATION_ID);
2480                out.attribute(null, ATTR_ID, id);
2481                out.endTag(null, TAG_AFFILIATION_ID);
2482            }
2483
2484            if (policy.mLastSecurityLogRetrievalTime >= 0) {
2485                out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2486                out.attribute(null, ATTR_VALUE,
2487                        Long.toString(policy.mLastSecurityLogRetrievalTime));
2488                out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2489            }
2490
2491            if (policy.mLastBugReportRequestTime >= 0) {
2492                out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2493                out.attribute(null, ATTR_VALUE,
2494                        Long.toString(policy.mLastBugReportRequestTime));
2495                out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2496            }
2497
2498            if (policy.mLastNetworkLogsRetrievalTime >= 0) {
2499                out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2500                out.attribute(null, ATTR_VALUE,
2501                        Long.toString(policy.mLastNetworkLogsRetrievalTime));
2502                out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2503            }
2504
2505            if (policy.mAdminBroadcastPending) {
2506                out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2507                out.attribute(null, ATTR_VALUE,
2508                        Boolean.toString(policy.mAdminBroadcastPending));
2509                out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2510            }
2511
2512            if (policy.mInitBundle != null) {
2513                out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2514                policy.mInitBundle.saveToXml(out);
2515                out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2516            }
2517
2518            out.endTag(null, "policies");
2519
2520            out.endDocument();
2521            stream.flush();
2522            FileUtils.sync(stream);
2523            stream.close();
2524            journal.commit();
2525            sendChangedNotification(userHandle);
2526        } catch (XmlPullParserException | IOException e) {
2527            Slog.w(LOG_TAG, "failed writing file", e);
2528            try {
2529                if (stream != null) {
2530                    stream.close();
2531                }
2532            } catch (IOException ex) {
2533                // Ignore
2534            }
2535            journal.rollback();
2536        }
2537    }
2538
2539    private void sendChangedNotification(int userHandle) {
2540        Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2541        intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2542        long ident = mInjector.binderClearCallingIdentity();
2543        try {
2544            mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2545        } finally {
2546            mInjector.binderRestoreCallingIdentity(ident);
2547        }
2548    }
2549
2550    private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2551        JournaledFile journal = makeJournaledFile(userHandle);
2552        FileInputStream stream = null;
2553        File file = journal.chooseForRead();
2554        boolean needsRewrite = false;
2555        try {
2556            stream = new FileInputStream(file);
2557            XmlPullParser parser = Xml.newPullParser();
2558            parser.setInput(stream, StandardCharsets.UTF_8.name());
2559
2560            int type;
2561            while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2562                    && type != XmlPullParser.START_TAG) {
2563            }
2564            String tag = parser.getName();
2565            if (!"policies".equals(tag)) {
2566                throw new XmlPullParserException(
2567                        "Settings do not start with policies tag: found " + tag);
2568            }
2569
2570            // Extract the permission provider component name if available
2571            String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2572            if (permissionProvider != null) {
2573                policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2574            }
2575            String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2576            if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2577                policy.mUserSetupComplete = true;
2578            }
2579            String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
2580            if (paired != null && Boolean.toString(true).equals(paired)) {
2581                policy.mPaired = true;
2582            }
2583            String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2584                    ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2585            if (deviceProvisioningConfigApplied != null
2586                    && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2587                policy.mDeviceProvisioningConfigApplied = true;
2588            }
2589            String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2590            if (!TextUtils.isEmpty(provisioningState)) {
2591                policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2592            }
2593            String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2594            if (!TextUtils.isEmpty(permissionPolicy)) {
2595                policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2596            }
2597            // Check for delegation compatibility with pre-O.
2598            // TODO(edmanp) remove in P.
2599            {
2600                final String certDelegate = parser.getAttributeValue(null,
2601                        ATTR_DELEGATED_CERT_INSTALLER);
2602                if (certDelegate != null) {
2603                    List<String> scopes = policy.mDelegationMap.get(certDelegate);
2604                    if (scopes == null) {
2605                        scopes = new ArrayList<>();
2606                        policy.mDelegationMap.put(certDelegate, scopes);
2607                    }
2608                    if (!scopes.contains(DELEGATION_CERT_INSTALL)) {
2609                        scopes.add(DELEGATION_CERT_INSTALL);
2610                        needsRewrite = true;
2611                    }
2612                }
2613                final String appRestrictionsDelegate = parser.getAttributeValue(null,
2614                        ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2615                if (appRestrictionsDelegate != null) {
2616                    List<String> scopes = policy.mDelegationMap.get(appRestrictionsDelegate);
2617                    if (scopes == null) {
2618                        scopes = new ArrayList<>();
2619                        policy.mDelegationMap.put(appRestrictionsDelegate, scopes);
2620                    }
2621                    if (!scopes.contains(DELEGATION_APP_RESTRICTIONS)) {
2622                        scopes.add(DELEGATION_APP_RESTRICTIONS);
2623                        needsRewrite = true;
2624                    }
2625                }
2626            }
2627
2628            type = parser.next();
2629            int outerDepth = parser.getDepth();
2630            policy.mLockTaskPackages.clear();
2631            policy.mAdminList.clear();
2632            policy.mAdminMap.clear();
2633            policy.mAffiliationIds.clear();
2634            while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2635                   && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2636                if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2637                    continue;
2638                }
2639                tag = parser.getName();
2640                if ("admin".equals(tag)) {
2641                    String name = parser.getAttributeValue(null, "name");
2642                    try {
2643                        DeviceAdminInfo dai = findAdmin(
2644                                ComponentName.unflattenFromString(name), userHandle,
2645                                /* throwForMissionPermission= */ false);
2646                        if (VERBOSE_LOG
2647                                && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2648                                != userHandle)) {
2649                            Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2650                                    + dai.getActivityInfo().applicationInfo.uid + " for user "
2651                                    + userHandle);
2652                        }
2653                        if (dai != null) {
2654                            ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2655                            ap.readFromXml(parser);
2656                            policy.mAdminMap.put(ap.info.getComponent(), ap);
2657                        }
2658                    } catch (RuntimeException e) {
2659                        Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2660                    }
2661                } else if ("delegation".equals(tag)) {
2662                    // Parse delegation info.
2663                    final String delegatePackage = parser.getAttributeValue(null,
2664                            "delegatePackage");
2665                    final String scope = parser.getAttributeValue(null, "scope");
2666
2667                    // Get a reference to the scopes list for the delegatePackage.
2668                    List<String> scopes = policy.mDelegationMap.get(delegatePackage);
2669                    // Or make a new list if none was found.
2670                    if (scopes == null) {
2671                        scopes = new ArrayList<>();
2672                        policy.mDelegationMap.put(delegatePackage, scopes);
2673                    }
2674                    // Add the new scope to the list of delegatePackage if it's not already there.
2675                    if (!scopes.contains(scope)) {
2676                        scopes.add(scope);
2677                    }
2678                } else if ("failed-password-attempts".equals(tag)) {
2679                    policy.mFailedPasswordAttempts = Integer.parseInt(
2680                            parser.getAttributeValue(null, "value"));
2681                } else if ("password-owner".equals(tag)) {
2682                    policy.mPasswordOwner = Integer.parseInt(
2683                            parser.getAttributeValue(null, "value"));
2684                } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2685                    policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2686                } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2687                    policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2688                } else if (TAG_STATUS_BAR.equals(tag)) {
2689                    policy.mStatusBarDisabled = Boolean.parseBoolean(
2690                            parser.getAttributeValue(null, ATTR_DISABLED));
2691                } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2692                    policy.doNotAskCredentialsOnBoot = true;
2693                } else if (TAG_AFFILIATION_ID.equals(tag)) {
2694                    policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID));
2695                } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) {
2696                    policy.mLastSecurityLogRetrievalTime = Long.parseLong(
2697                            parser.getAttributeValue(null, ATTR_VALUE));
2698                } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) {
2699                    policy.mLastBugReportRequestTime = Long.parseLong(
2700                            parser.getAttributeValue(null, ATTR_VALUE));
2701                } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) {
2702                    policy.mLastNetworkLogsRetrievalTime = Long.parseLong(
2703                            parser.getAttributeValue(null, ATTR_VALUE));
2704                } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2705                    String pending = parser.getAttributeValue(null, ATTR_VALUE);
2706                    policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2707                } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2708                    policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2709                } else if ("active-password".equals(tag)) {
2710                    if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2711                        // Remove this from FBE devices
2712                        needsRewrite = true;
2713                    } else {
2714                        final PasswordMetrics m = policy.mActivePasswordMetrics;
2715                        m.quality = Integer.parseInt(parser.getAttributeValue(null, "quality"));
2716                        m.length = Integer.parseInt(parser.getAttributeValue(null, "length"));
2717                        m.upperCase = Integer.parseInt(parser.getAttributeValue(null, "uppercase"));
2718                        m.lowerCase = Integer.parseInt(parser.getAttributeValue(null, "lowercase"));
2719                        m.letters = Integer.parseInt(parser.getAttributeValue(null, "letters"));
2720                        m.numeric = Integer.parseInt(parser.getAttributeValue(null, "numeric"));
2721                        m.symbols = Integer.parseInt(parser.getAttributeValue(null, "symbols"));
2722                        m.nonLetter = Integer.parseInt(parser.getAttributeValue(null, "nonletter"));
2723                    }
2724                } else {
2725                    Slog.w(LOG_TAG, "Unknown tag: " + tag);
2726                    XmlUtils.skipCurrentTag(parser);
2727                }
2728            }
2729        } catch (FileNotFoundException e) {
2730            // Don't be noisy, this is normal if we haven't defined any policies.
2731        } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2732                | IndexOutOfBoundsException e) {
2733            Slog.w(LOG_TAG, "failed parsing " + file, e);
2734        }
2735        try {
2736            if (stream != null) {
2737                stream.close();
2738            }
2739        } catch (IOException e) {
2740            // Ignore
2741        }
2742
2743        // Generate a list of admins from the admin map
2744        policy.mAdminList.addAll(policy.mAdminMap.values());
2745
2746        // Might need to upgrade the file by rewriting it
2747        if (needsRewrite) {
2748            saveSettingsLocked(userHandle);
2749        }
2750
2751        validatePasswordOwnerLocked(policy);
2752        updateMaximumTimeToLockLocked(userHandle);
2753        updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2754        if (policy.mStatusBarDisabled) {
2755            setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2756        }
2757    }
2758
2759    private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2760        long ident = mInjector.binderClearCallingIdentity();
2761        try {
2762            mInjector.getIActivityManager()
2763                    .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2764        } catch (RemoteException e) {
2765            // Not gonna happen.
2766        } finally {
2767            mInjector.binderRestoreCallingIdentity(ident);
2768        }
2769    }
2770
2771    private void updateDeviceOwnerLocked() {
2772        long ident = mInjector.binderClearCallingIdentity();
2773        try {
2774            // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2775            // user id and also protect all other DAs too.
2776            final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2777            if (deviceOwnerComponent != null) {
2778                mInjector.getIActivityManager()
2779                        .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2780            }
2781        } catch (RemoteException e) {
2782            // Not gonna happen.
2783        } finally {
2784            mInjector.binderRestoreCallingIdentity(ident);
2785        }
2786    }
2787
2788    static void validateQualityConstant(int quality) {
2789        switch (quality) {
2790            case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2791            case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2792            case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2793            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2794            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2795            case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2796            case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2797            case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2798            case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2799                return;
2800        }
2801        throw new IllegalArgumentException("Invalid quality constant: 0x"
2802                + Integer.toHexString(quality));
2803    }
2804
2805    void validatePasswordOwnerLocked(DevicePolicyData policy) {
2806        if (policy.mPasswordOwner >= 0) {
2807            boolean haveOwner = false;
2808            for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2809                if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2810                    haveOwner = true;
2811                    break;
2812                }
2813            }
2814            if (!haveOwner) {
2815                Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2816                        + " no longer active; disabling");
2817                policy.mPasswordOwner = -1;
2818            }
2819        }
2820    }
2821
2822    @VisibleForTesting
2823    void systemReady(int phase) {
2824        if (!mHasFeature) {
2825            return;
2826        }
2827        switch (phase) {
2828            case SystemService.PHASE_LOCK_SETTINGS_READY:
2829                onLockSettingsReady();
2830                break;
2831            case SystemService.PHASE_BOOT_COMPLETED:
2832                ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2833                break;
2834        }
2835    }
2836
2837    private void onLockSettingsReady() {
2838        getUserData(UserHandle.USER_SYSTEM);
2839        loadOwners();
2840        cleanUpOldUsers();
2841
2842        onStartUser(UserHandle.USER_SYSTEM);
2843
2844        // Register an observer for watching for user setup complete.
2845        new SetupContentObserver(mHandler).register();
2846        // Initialize the user setup state, to handle the upgrade case.
2847        updateUserSetupCompleteAndPaired();
2848
2849        List<String> packageList;
2850        synchronized (this) {
2851            packageList = getKeepUninstalledPackagesLocked();
2852        }
2853        if (packageList != null) {
2854            mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2855        }
2856
2857        synchronized (this) {
2858            // push the force-ephemeral-users policy to the user manager.
2859            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2860            if (deviceOwner != null) {
2861                mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2862            }
2863        }
2864    }
2865
2866    private void ensureDeviceOwnerUserStarted() {
2867        final int userId;
2868        synchronized (this) {
2869            if (!mOwners.hasDeviceOwner()) {
2870                return;
2871            }
2872            userId = mOwners.getDeviceOwnerUserId();
2873        }
2874        if (VERBOSE_LOG) {
2875            Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2876        }
2877        if (userId != UserHandle.USER_SYSTEM) {
2878            try {
2879                mInjector.getIActivityManager().startUserInBackground(userId);
2880
2881                // STOPSHIP Prevent the DO user from being killed.
2882
2883            } catch (RemoteException e) {
2884                Slog.w(LOG_TAG, "Exception starting user", e);
2885            }
2886        }
2887    }
2888
2889    private void onStartUser(int userId) {
2890        updateScreenCaptureDisabledInWindowManager(userId,
2891                getScreenCaptureDisabled(null, userId));
2892        pushUserRestrictions(userId);
2893    }
2894
2895    private void cleanUpOldUsers() {
2896        // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2897        // before reboot
2898        Set<Integer> usersWithProfileOwners;
2899        Set<Integer> usersWithData;
2900        synchronized(this) {
2901            usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2902            usersWithData = new ArraySet<>();
2903            for (int i = 0; i < mUserData.size(); i++) {
2904                usersWithData.add(mUserData.keyAt(i));
2905            }
2906        }
2907        List<UserInfo> allUsers = mUserManager.getUsers();
2908
2909        Set<Integer> deletedUsers = new ArraySet<>();
2910        deletedUsers.addAll(usersWithProfileOwners);
2911        deletedUsers.addAll(usersWithData);
2912        for (UserInfo userInfo : allUsers) {
2913            deletedUsers.remove(userInfo.id);
2914        }
2915        for (Integer userId : deletedUsers) {
2916            removeUserData(userId);
2917        }
2918    }
2919
2920    private void handlePasswordExpirationNotification(int userHandle) {
2921        final Bundle adminExtras = new Bundle();
2922        adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
2923
2924        synchronized (this) {
2925            final long now = System.currentTimeMillis();
2926
2927            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2928                    userHandle, /* parent */ false);
2929            final int N = admins.size();
2930            for (int i = 0; i < N; i++) {
2931                ActiveAdmin admin = admins.get(i);
2932                if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2933                        && admin.passwordExpirationTimeout > 0L
2934                        && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2935                        && admin.passwordExpirationDate > 0L) {
2936                    sendAdminCommandLocked(admin,
2937                            DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null);
2938                }
2939            }
2940            setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2941        }
2942    }
2943
2944    private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2945        @Override
2946        protected Void doInBackground(Integer... params) {
2947            int userHandle = params[0];
2948
2949            if (userHandle == UserHandle.USER_ALL) {
2950                for (UserInfo userInfo : mUserManager.getUsers(true)) {
2951                    manageNotification(userInfo.getUserHandle());
2952                }
2953            } else {
2954                manageNotification(UserHandle.of(userHandle));
2955            }
2956            return null;
2957        }
2958
2959        private void manageNotification(UserHandle userHandle) {
2960            if (!mUserManager.isUserUnlocked(userHandle)) {
2961                return;
2962            }
2963
2964            // Call out to KeyChain to check for CAs which are waiting for approval.
2965            final List<String> pendingCertificates;
2966            try {
2967                pendingCertificates = getInstalledCaCertificates(userHandle);
2968            } catch (RemoteException | RuntimeException e) {
2969                Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2970                return;
2971            }
2972
2973            synchronized (DevicePolicyManagerService.this) {
2974                final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2975
2976                // Remove deleted certificates. Flush xml if necessary.
2977                if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2978                    saveSettingsLocked(userHandle.getIdentifier());
2979                }
2980                // Trim to approved certificates.
2981                pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2982            }
2983
2984            if (pendingCertificates.isEmpty()) {
2985                mInjector.getNotificationManager().cancelAsUser(
2986                        null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2987                return;
2988            }
2989
2990            // Build and show a warning notification
2991            int smallIconId;
2992            String contentText;
2993            int parentUserId = userHandle.getIdentifier();
2994            if (getProfileOwner(userHandle.getIdentifier()) != null) {
2995                contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2996                        getProfileOwnerName(userHandle.getIdentifier()));
2997                smallIconId = R.drawable.stat_sys_certificate_info;
2998                parentUserId = getProfileParentId(userHandle.getIdentifier());
2999            } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
3000                contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
3001                        getDeviceOwnerName());
3002                smallIconId = R.drawable.stat_sys_certificate_info;
3003            } else {
3004                contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
3005                smallIconId = android.R.drawable.stat_sys_warning;
3006            }
3007
3008            final int numberOfCertificates = pendingCertificates.size();
3009            Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
3010            dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
3011            dialogIntent.setPackage("com.android.settings");
3012            dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
3013            dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
3014            PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
3015                    dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
3016                    new UserHandle(parentUserId));
3017
3018            final Context userContext;
3019            try {
3020                final String packageName = mContext.getPackageName();
3021                userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
3022            } catch (PackageManager.NameNotFoundException e) {
3023                Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
3024                return;
3025            }
3026            final Notification noti = new Notification.Builder(userContext)
3027                .setSmallIcon(smallIconId)
3028                .setContentTitle(mContext.getResources().getQuantityText(
3029                        R.plurals.ssl_ca_cert_warning, numberOfCertificates))
3030                .setContentText(contentText)
3031                .setContentIntent(notifyIntent)
3032                .setPriority(Notification.PRIORITY_HIGH)
3033                .setShowWhen(false)
3034                .setColor(mContext.getColor(
3035                        com.android.internal.R.color.system_notification_accent_color))
3036                .build();
3037
3038            mInjector.getNotificationManager().notifyAsUser(
3039                    null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
3040        }
3041
3042        private List<String> getInstalledCaCertificates(UserHandle userHandle)
3043                throws RemoteException, RuntimeException {
3044            KeyChainConnection conn = null;
3045            try {
3046                conn = KeyChain.bindAsUser(mContext, userHandle);
3047                List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
3048                List<String> result = new ArrayList<>(aliases.size());
3049                for (int i = 0; i < aliases.size(); i++) {
3050                    result.add(aliases.get(i).string);
3051                }
3052                return result;
3053            } catch (InterruptedException e) {
3054                Thread.currentThread().interrupt();
3055                return null;
3056            } catch (AssertionError e) {
3057                throw new RuntimeException(e);
3058            } finally {
3059                if (conn != null) {
3060                    conn.close();
3061                }
3062            }
3063        }
3064    }
3065
3066    /**
3067     * @param adminReceiver The admin to add
3068     * @param refreshing true = update an active admin, no error
3069     */
3070    @Override
3071    public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
3072        if (!mHasFeature) {
3073            return;
3074        }
3075        setActiveAdmin(adminReceiver, refreshing, userHandle, null);
3076    }
3077
3078    private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
3079            Bundle onEnableData) {
3080        mContext.enforceCallingOrSelfPermission(
3081                android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3082        enforceFullCrossUsersPermission(userHandle);
3083
3084        DevicePolicyData policy = getUserData(userHandle);
3085        DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
3086                /* throwForMissionPermission= */ true);
3087        if (info == null) {
3088            throw new IllegalArgumentException("Bad admin: " + adminReceiver);
3089        }
3090        if (!info.getActivityInfo().applicationInfo.isInternal()) {
3091            throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
3092                    + adminReceiver);
3093        }
3094        synchronized (this) {
3095            long ident = mInjector.binderClearCallingIdentity();
3096            try {
3097                final ActiveAdmin existingAdmin
3098                        = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3099                if (!refreshing && existingAdmin != null) {
3100                    throw new IllegalArgumentException("Admin is already added");
3101                }
3102                if (policy.mRemovingAdmins.contains(adminReceiver)) {
3103                    throw new IllegalArgumentException(
3104                            "Trying to set an admin which is being removed");
3105                }
3106                ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
3107                newAdmin.testOnlyAdmin =
3108                        (existingAdmin != null) ? existingAdmin.testOnlyAdmin
3109                                : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
3110                policy.mAdminMap.put(adminReceiver, newAdmin);
3111                int replaceIndex = -1;
3112                final int N = policy.mAdminList.size();
3113                for (int i=0; i < N; i++) {
3114                    ActiveAdmin oldAdmin = policy.mAdminList.get(i);
3115                    if (oldAdmin.info.getComponent().equals(adminReceiver)) {
3116                        replaceIndex = i;
3117                        break;
3118                    }
3119                }
3120                if (replaceIndex == -1) {
3121                    policy.mAdminList.add(newAdmin);
3122                    enableIfNecessary(info.getPackageName(), userHandle);
3123                } else {
3124                    policy.mAdminList.set(replaceIndex, newAdmin);
3125                }
3126                saveSettingsLocked(userHandle);
3127                sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3128                        onEnableData, null);
3129            } finally {
3130                mInjector.binderRestoreCallingIdentity(ident);
3131            }
3132        }
3133    }
3134
3135    @Override
3136    public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
3137        if (!mHasFeature) {
3138            return false;
3139        }
3140        enforceFullCrossUsersPermission(userHandle);
3141        synchronized (this) {
3142            return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
3143        }
3144    }
3145
3146    @Override
3147    public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
3148        if (!mHasFeature) {
3149            return false;
3150        }
3151        enforceFullCrossUsersPermission(userHandle);
3152        synchronized (this) {
3153            DevicePolicyData policyData = getUserData(userHandle);
3154            return policyData.mRemovingAdmins.contains(adminReceiver);
3155        }
3156    }
3157
3158    @Override
3159    public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
3160        if (!mHasFeature) {
3161            return false;
3162        }
3163        enforceFullCrossUsersPermission(userHandle);
3164        synchronized (this) {
3165            ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3166            if (administrator == null) {
3167                throw new SecurityException("No active admin " + adminReceiver);
3168            }
3169            return administrator.info.usesPolicy(policyId);
3170        }
3171    }
3172
3173    @Override
3174    @SuppressWarnings("unchecked")
3175    public List<ComponentName> getActiveAdmins(int userHandle) {
3176        if (!mHasFeature) {
3177            return Collections.EMPTY_LIST;
3178        }
3179
3180        enforceFullCrossUsersPermission(userHandle);
3181        synchronized (this) {
3182            DevicePolicyData policy = getUserData(userHandle);
3183            final int N = policy.mAdminList.size();
3184            if (N <= 0) {
3185                return null;
3186            }
3187            ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3188            for (int i=0; i<N; i++) {
3189                res.add(policy.mAdminList.get(i).info.getComponent());
3190            }
3191            return res;
3192        }
3193    }
3194
3195    @Override
3196    public boolean packageHasActiveAdmins(String packageName, int userHandle) {
3197        if (!mHasFeature) {
3198            return false;
3199        }
3200        enforceFullCrossUsersPermission(userHandle);
3201        synchronized (this) {
3202            DevicePolicyData policy = getUserData(userHandle);
3203            final int N = policy.mAdminList.size();
3204            for (int i=0; i<N; i++) {
3205                if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
3206                    return true;
3207                }
3208            }
3209            return false;
3210        }
3211    }
3212
3213    public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
3214        if (!mHasFeature) {
3215            return;
3216        }
3217        Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
3218        enforceShell("forceRemoveActiveAdmin");
3219        long ident = mInjector.binderClearCallingIdentity();
3220        try {
3221            synchronized (this)  {
3222                if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
3223                    throw new SecurityException("Attempt to remove non-test admin "
3224                            + adminReceiver + " " + userHandle);
3225                }
3226
3227                // If admin is a device or profile owner tidy that up first.
3228                if (isDeviceOwner(adminReceiver, userHandle)) {
3229                    clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3230                    clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userHandle));
3231                }
3232                if (isProfileOwner(adminReceiver, userHandle)) {
3233                    final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3234                            userHandle, /* parent */ false);
3235                    clearProfileOwnerLocked(admin, userHandle);
3236                }
3237            }
3238            // Remove the admin skipping sending the broadcast.
3239            removeAdminArtifacts(adminReceiver, userHandle);
3240            Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3241        } finally {
3242            mInjector.binderRestoreCallingIdentity(ident);
3243        }
3244    }
3245
3246    // It's temporary solution to clear DISALLOW_ADD_USER after CTS
3247    // STOPSHIP(b/31952368) when the restriction is moved from system to the device owner,
3248    // it can be removed.
3249    private void clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle) {
3250        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
3251            mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle);
3252        }
3253    }
3254
3255    /**
3256     * Return if a given package has testOnly="true", in which case we'll relax certain rules
3257     * for CTS.
3258     *
3259     * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
3260     * to check wehter an active admin is test-only or not.
3261     *
3262     * The system allows this flag to be changed when an app is updated, which is not good
3263     * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3264     * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3265     */
3266    private boolean isPackageTestOnly(String packageName, int userHandle) {
3267        final ApplicationInfo ai;
3268        try {
3269            ai = mIPackageManager.getApplicationInfo(packageName,
3270                    (PackageManager.MATCH_DIRECT_BOOT_AWARE
3271                            | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3272        } catch (RemoteException e) {
3273            throw new IllegalStateException(e);
3274        }
3275        if (ai == null) {
3276            throw new IllegalStateException("Couldn't find package: "
3277                    + packageName + " on user " + userHandle);
3278        }
3279        return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3280    }
3281
3282    /**
3283     * See {@link #isPackageTestOnly}.
3284     */
3285    private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3286        final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3287        return (admin != null) && admin.testOnlyAdmin;
3288    }
3289
3290    private void enforceShell(String method) {
3291        final int callingUid = Binder.getCallingUid();
3292        if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3293            throw new SecurityException("Non-shell user attempted to call " + method);
3294        }
3295    }
3296
3297    @Override
3298    public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3299        if (!mHasFeature) {
3300            return;
3301        }
3302        enforceFullCrossUsersPermission(userHandle);
3303        enforceUserUnlocked(userHandle);
3304        synchronized (this) {
3305            ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3306            if (admin == null) {
3307                return;
3308            }
3309            // Active device/profile owners must remain active admins.
3310            if (isDeviceOwner(adminReceiver, userHandle)
3311                    || isProfileOwner(adminReceiver, userHandle)) {
3312                Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3313                        adminReceiver);
3314                return;
3315            }
3316            if (admin.getUid() != mInjector.binderGetCallingUid()) {
3317                mContext.enforceCallingOrSelfPermission(
3318                        android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3319            }
3320            long ident = mInjector.binderClearCallingIdentity();
3321            try {
3322                removeActiveAdminLocked(adminReceiver, userHandle);
3323            } finally {
3324                mInjector.binderRestoreCallingIdentity(ident);
3325            }
3326        }
3327    }
3328
3329    @Override
3330    public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3331        ComponentName profileOwner = getProfileOwner(userHandle);
3332        // Profile challenge is supported on N or newer release.
3333        return profileOwner != null &&
3334                getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3335    }
3336
3337    @Override
3338    public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3339        if (!mHasFeature) {
3340            return;
3341        }
3342        Preconditions.checkNotNull(who, "ComponentName is null");
3343        validateQualityConstant(quality);
3344
3345        synchronized (this) {
3346            ActiveAdmin ap = getActiveAdminForCallerLocked(
3347                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3348            if (ap.minimumPasswordMetrics.quality != quality) {
3349                ap.minimumPasswordMetrics.quality = quality;
3350                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3351            }
3352        }
3353    }
3354
3355    @Override
3356    public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3357        if (!mHasFeature) {
3358            return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3359        }
3360        enforceFullCrossUsersPermission(userHandle);
3361        synchronized (this) {
3362            int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3363
3364            if (who != null) {
3365                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3366                return admin != null ? admin.minimumPasswordMetrics.quality : mode;
3367            }
3368
3369            // Return the strictest policy across all participating admins.
3370            List<ActiveAdmin> admins =
3371                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3372            final int N = admins.size();
3373            for (int i = 0; i < N; i++) {
3374                ActiveAdmin admin = admins.get(i);
3375                if (mode < admin.minimumPasswordMetrics.quality) {
3376                    mode = admin.minimumPasswordMetrics.quality;
3377                }
3378            }
3379            return mode;
3380        }
3381    }
3382
3383    private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3384            int userHandle, boolean parent) {
3385        if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3386            // If this user has a separate challenge, only return its restrictions.
3387            return getUserDataUnchecked(userHandle).mAdminList;
3388        } else {
3389            // Return all admins for this user and the profiles that are visible from this
3390            // user that do not use a separate work challenge.
3391            ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3392            for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3393                DevicePolicyData policy = getUserData(userInfo.id);
3394                if (!userInfo.isManagedProfile()) {
3395                    admins.addAll(policy.mAdminList);
3396                } else {
3397                    // For managed profiles, we always include the policies set on the parent
3398                    // profile. Additionally, we include the ones set on the managed profile
3399                    // if no separate challenge is in place.
3400                    boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3401                    final int N = policy.mAdminList.size();
3402                    for (int i = 0; i < N; i++) {
3403                        ActiveAdmin admin = policy.mAdminList.get(i);
3404                        if (admin.hasParentActiveAdmin()) {
3405                            admins.add(admin.getParentActiveAdmin());
3406                        }
3407                        if (!hasSeparateChallenge) {
3408                            admins.add(admin);
3409                        }
3410                    }
3411                }
3412            }
3413            return admins;
3414        }
3415    }
3416
3417    private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3418        long ident = mInjector.binderClearCallingIdentity();
3419        try {
3420            return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3421        } finally {
3422            mInjector.binderRestoreCallingIdentity(ident);
3423        }
3424    }
3425
3426    @Override
3427    public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3428        if (!mHasFeature) {
3429            return;
3430        }
3431        Preconditions.checkNotNull(who, "ComponentName is null");
3432        synchronized (this) {
3433            ActiveAdmin ap = getActiveAdminForCallerLocked(
3434                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3435            if (ap.minimumPasswordMetrics.length != length) {
3436                ap.minimumPasswordMetrics.length = length;
3437                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3438            }
3439        }
3440    }
3441
3442    @Override
3443    public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3444        if (!mHasFeature) {
3445            return 0;
3446        }
3447        enforceFullCrossUsersPermission(userHandle);
3448        synchronized (this) {
3449            int length = 0;
3450
3451            if (who != null) {
3452                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3453                return admin != null ? admin.minimumPasswordMetrics.length : length;
3454            }
3455
3456            // Return the strictest policy across all participating admins.
3457            List<ActiveAdmin> admins =
3458                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3459            final int N = admins.size();
3460            for (int i = 0; i < N; i++) {
3461                ActiveAdmin admin = admins.get(i);
3462                if (length < admin.minimumPasswordMetrics.length) {
3463                    length = admin.minimumPasswordMetrics.length;
3464                }
3465            }
3466            return length;
3467        }
3468    }
3469
3470    @Override
3471    public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3472        if (!mHasFeature) {
3473            return;
3474        }
3475        Preconditions.checkNotNull(who, "ComponentName is null");
3476        synchronized (this) {
3477            ActiveAdmin ap = getActiveAdminForCallerLocked(
3478                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3479            if (ap.passwordHistoryLength != length) {
3480                ap.passwordHistoryLength = length;
3481                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3482            }
3483        }
3484    }
3485
3486    @Override
3487    public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3488        if (!mHasFeature) {
3489            return 0;
3490        }
3491        enforceFullCrossUsersPermission(userHandle);
3492        synchronized (this) {
3493            int length = 0;
3494
3495            if (who != null) {
3496                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3497                return admin != null ? admin.passwordHistoryLength : length;
3498            }
3499
3500            // Return the strictest policy across all participating admins.
3501            List<ActiveAdmin> admins =
3502                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3503            final int N = admins.size();
3504            for (int i = 0; i < N; i++) {
3505                ActiveAdmin admin = admins.get(i);
3506                if (length < admin.passwordHistoryLength) {
3507                    length = admin.passwordHistoryLength;
3508                }
3509            }
3510
3511            return length;
3512        }
3513    }
3514
3515    @Override
3516    public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3517        if (!mHasFeature) {
3518            return;
3519        }
3520        Preconditions.checkNotNull(who, "ComponentName is null");
3521        Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3522        final int userHandle = mInjector.userHandleGetCallingUserId();
3523        synchronized (this) {
3524            ActiveAdmin ap = getActiveAdminForCallerLocked(
3525                    who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3526            // Calling this API automatically bumps the expiration date
3527            final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3528            ap.passwordExpirationDate = expiration;
3529            ap.passwordExpirationTimeout = timeout;
3530            if (timeout > 0L) {
3531                Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3532                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3533                        .format(new Date(expiration)));
3534            }
3535            saveSettingsLocked(userHandle);
3536
3537            // in case this is the first one, set the alarm on the appropriate user.
3538            setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3539        }
3540    }
3541
3542    /**
3543     * Return a single admin's expiration cycle time, or the min of all cycle times.
3544     * Returns 0 if not configured.
3545     */
3546    @Override
3547    public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3548        if (!mHasFeature) {
3549            return 0L;
3550        }
3551        enforceFullCrossUsersPermission(userHandle);
3552        synchronized (this) {
3553            long timeout = 0L;
3554
3555            if (who != null) {
3556                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3557                return admin != null ? admin.passwordExpirationTimeout : timeout;
3558            }
3559
3560            // Return the strictest policy across all participating admins.
3561            List<ActiveAdmin> admins =
3562                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3563            final int N = admins.size();
3564            for (int i = 0; i < N; i++) {
3565                ActiveAdmin admin = admins.get(i);
3566                if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3567                        && timeout > admin.passwordExpirationTimeout)) {
3568                    timeout = admin.passwordExpirationTimeout;
3569                }
3570            }
3571            return timeout;
3572        }
3573    }
3574
3575    @Override
3576    public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3577        final int userId = UserHandle.getCallingUserId();
3578        List<String> changedProviders = null;
3579
3580        synchronized (this) {
3581            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3582                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3583            if (activeAdmin.crossProfileWidgetProviders == null) {
3584                activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3585            }
3586            List<String> providers = activeAdmin.crossProfileWidgetProviders;
3587            if (!providers.contains(packageName)) {
3588                providers.add(packageName);
3589                changedProviders = new ArrayList<>(providers);
3590                saveSettingsLocked(userId);
3591            }
3592        }
3593
3594        if (changedProviders != null) {
3595            mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3596            return true;
3597        }
3598
3599        return false;
3600    }
3601
3602    @Override
3603    public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3604        final int userId = UserHandle.getCallingUserId();
3605        List<String> changedProviders = null;
3606
3607        synchronized (this) {
3608            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3609                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3610            if (activeAdmin.crossProfileWidgetProviders == null
3611                    || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3612                return false;
3613            }
3614            List<String> providers = activeAdmin.crossProfileWidgetProviders;
3615            if (providers.remove(packageName)) {
3616                changedProviders = new ArrayList<>(providers);
3617                saveSettingsLocked(userId);
3618            }
3619        }
3620
3621        if (changedProviders != null) {
3622            mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3623            return true;
3624        }
3625
3626        return false;
3627    }
3628
3629    @Override
3630    public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3631        synchronized (this) {
3632            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3633                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3634            if (activeAdmin.crossProfileWidgetProviders == null
3635                    || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3636                return null;
3637            }
3638            if (mInjector.binderIsCallingUidMyUid()) {
3639                return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3640            } else {
3641                return activeAdmin.crossProfileWidgetProviders;
3642            }
3643        }
3644    }
3645
3646    /**
3647     * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3648     * Returns 0 if not configured.
3649     */
3650    private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3651        long timeout = 0L;
3652
3653        if (who != null) {
3654            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3655            return admin != null ? admin.passwordExpirationDate : timeout;
3656        }
3657
3658        // Return the strictest policy across all participating admins.
3659        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3660        final int N = admins.size();
3661        for (int i = 0; i < N; i++) {
3662            ActiveAdmin admin = admins.get(i);
3663            if (timeout == 0L || (admin.passwordExpirationDate != 0
3664                    && timeout > admin.passwordExpirationDate)) {
3665                timeout = admin.passwordExpirationDate;
3666            }
3667        }
3668        return timeout;
3669    }
3670
3671    @Override
3672    public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3673        if (!mHasFeature) {
3674            return 0L;
3675        }
3676        enforceFullCrossUsersPermission(userHandle);
3677        synchronized (this) {
3678            return getPasswordExpirationLocked(who, userHandle, parent);
3679        }
3680    }
3681
3682    @Override
3683    public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3684        if (!mHasFeature) {
3685            return;
3686        }
3687        Preconditions.checkNotNull(who, "ComponentName is null");
3688        synchronized (this) {
3689            ActiveAdmin ap = getActiveAdminForCallerLocked(
3690                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3691            if (ap.minimumPasswordMetrics.upperCase != length) {
3692                ap.minimumPasswordMetrics.upperCase = length;
3693                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3694            }
3695        }
3696    }
3697
3698    @Override
3699    public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3700        if (!mHasFeature) {
3701            return 0;
3702        }
3703        enforceFullCrossUsersPermission(userHandle);
3704        synchronized (this) {
3705            int length = 0;
3706
3707            if (who != null) {
3708                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3709                return admin != null ? admin.minimumPasswordMetrics.upperCase : length;
3710            }
3711
3712            // Return the strictest policy across all participating admins.
3713            List<ActiveAdmin> admins =
3714                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3715            final int N = admins.size();
3716            for (int i = 0; i < N; i++) {
3717                ActiveAdmin admin = admins.get(i);
3718                if (length < admin.minimumPasswordMetrics.upperCase) {
3719                    length = admin.minimumPasswordMetrics.upperCase;
3720                }
3721            }
3722            return length;
3723        }
3724    }
3725
3726    @Override
3727    public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3728        Preconditions.checkNotNull(who, "ComponentName is null");
3729        synchronized (this) {
3730            ActiveAdmin ap = getActiveAdminForCallerLocked(
3731                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3732            if (ap.minimumPasswordMetrics.lowerCase != length) {
3733                ap.minimumPasswordMetrics.lowerCase = length;
3734                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3735            }
3736        }
3737    }
3738
3739    @Override
3740    public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3741        if (!mHasFeature) {
3742            return 0;
3743        }
3744        enforceFullCrossUsersPermission(userHandle);
3745        synchronized (this) {
3746            int length = 0;
3747
3748            if (who != null) {
3749                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3750                return admin != null ? admin.minimumPasswordMetrics.lowerCase : length;
3751            }
3752
3753            // Return the strictest policy across all participating admins.
3754            List<ActiveAdmin> admins =
3755                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3756            final int N = admins.size();
3757            for (int i = 0; i < N; i++) {
3758                ActiveAdmin admin = admins.get(i);
3759                if (length < admin.minimumPasswordMetrics.lowerCase) {
3760                    length = admin.minimumPasswordMetrics.lowerCase;
3761                }
3762            }
3763            return length;
3764        }
3765    }
3766
3767    @Override
3768    public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3769        if (!mHasFeature) {
3770            return;
3771        }
3772        Preconditions.checkNotNull(who, "ComponentName is null");
3773        synchronized (this) {
3774            ActiveAdmin ap = getActiveAdminForCallerLocked(
3775                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3776            if (ap.minimumPasswordMetrics.letters != length) {
3777                ap.minimumPasswordMetrics.letters = length;
3778                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3779            }
3780        }
3781    }
3782
3783    @Override
3784    public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3785        if (!mHasFeature) {
3786            return 0;
3787        }
3788        enforceFullCrossUsersPermission(userHandle);
3789        synchronized (this) {
3790            int length = 0;
3791
3792            if (who != null) {
3793                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3794                return admin != null ? admin.minimumPasswordMetrics.letters : length;
3795            }
3796
3797            // Return the strictest policy across all participating admins.
3798            List<ActiveAdmin> admins =
3799                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3800            final int N = admins.size();
3801            for (int i = 0; i < N; i++) {
3802                ActiveAdmin admin = admins.get(i);
3803                if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3804                    continue;
3805                }
3806                if (length < admin.minimumPasswordMetrics.letters) {
3807                    length = admin.minimumPasswordMetrics.letters;
3808                }
3809            }
3810            return length;
3811        }
3812    }
3813
3814    @Override
3815    public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3816        if (!mHasFeature) {
3817            return;
3818        }
3819        Preconditions.checkNotNull(who, "ComponentName is null");
3820        synchronized (this) {
3821            ActiveAdmin ap = getActiveAdminForCallerLocked(
3822                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3823            if (ap.minimumPasswordMetrics.numeric != length) {
3824                ap.minimumPasswordMetrics.numeric = length;
3825                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3826            }
3827        }
3828    }
3829
3830    @Override
3831    public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3832        if (!mHasFeature) {
3833            return 0;
3834        }
3835        enforceFullCrossUsersPermission(userHandle);
3836        synchronized (this) {
3837            int length = 0;
3838
3839            if (who != null) {
3840                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3841                return admin != null ? admin.minimumPasswordMetrics.numeric : length;
3842            }
3843
3844            // Return the strictest policy across all participating admins.
3845            List<ActiveAdmin> admins =
3846                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3847            final int N = admins.size();
3848            for (int i = 0; i < N; i++) {
3849                ActiveAdmin admin = admins.get(i);
3850                if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3851                    continue;
3852                }
3853                if (length < admin.minimumPasswordMetrics.numeric) {
3854                    length = admin.minimumPasswordMetrics.numeric;
3855                }
3856            }
3857            return length;
3858        }
3859    }
3860
3861    @Override
3862    public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3863        if (!mHasFeature) {
3864            return;
3865        }
3866        Preconditions.checkNotNull(who, "ComponentName is null");
3867        synchronized (this) {
3868            ActiveAdmin ap = getActiveAdminForCallerLocked(
3869                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3870            if (ap.minimumPasswordMetrics.symbols != length) {
3871                ap.minimumPasswordMetrics.symbols = length;
3872                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3873            }
3874        }
3875    }
3876
3877    @Override
3878    public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3879        if (!mHasFeature) {
3880            return 0;
3881        }
3882        enforceFullCrossUsersPermission(userHandle);
3883        synchronized (this) {
3884            int length = 0;
3885
3886            if (who != null) {
3887                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3888                return admin != null ? admin.minimumPasswordMetrics.symbols : length;
3889            }
3890
3891            // Return the strictest policy across all participating admins.
3892            List<ActiveAdmin> admins =
3893                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3894            final int N = admins.size();
3895            for (int i = 0; i < N; i++) {
3896                ActiveAdmin admin = admins.get(i);
3897                if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3898                    continue;
3899                }
3900                if (length < admin.minimumPasswordMetrics.symbols) {
3901                    length = admin.minimumPasswordMetrics.symbols;
3902                }
3903            }
3904            return length;
3905        }
3906    }
3907
3908    @Override
3909    public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3910        if (!mHasFeature) {
3911            return;
3912        }
3913        Preconditions.checkNotNull(who, "ComponentName is null");
3914        synchronized (this) {
3915            ActiveAdmin ap = getActiveAdminForCallerLocked(
3916                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3917            if (ap.minimumPasswordMetrics.nonLetter != length) {
3918                ap.minimumPasswordMetrics.nonLetter = length;
3919                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3920            }
3921        }
3922    }
3923
3924    @Override
3925    public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3926        if (!mHasFeature) {
3927            return 0;
3928        }
3929        enforceFullCrossUsersPermission(userHandle);
3930        synchronized (this) {
3931            int length = 0;
3932
3933            if (who != null) {
3934                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3935                return admin != null ? admin.minimumPasswordMetrics.nonLetter : length;
3936            }
3937
3938            // Return the strictest policy across all participating admins.
3939            List<ActiveAdmin> admins =
3940                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3941            final int N = admins.size();
3942            for (int i = 0; i < N; i++) {
3943                ActiveAdmin admin = admins.get(i);
3944                if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3945                    continue;
3946                }
3947                if (length < admin.minimumPasswordMetrics.nonLetter) {
3948                    length = admin.minimumPasswordMetrics.nonLetter;
3949                }
3950            }
3951            return length;
3952        }
3953    }
3954
3955    @Override
3956    public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3957        if (!mHasFeature) {
3958            return true;
3959        }
3960        enforceFullCrossUsersPermission(userHandle);
3961
3962        synchronized (this) {
3963            // This API can only be called by an active device admin,
3964            // so try to retrieve it to check that the caller is one.
3965            getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3966            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3967            return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3968        }
3969    }
3970
3971    @Override
3972    public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3973        if (!mHasFeature) {
3974            return true;
3975        }
3976        enforceFullCrossUsersPermission(userHandle);
3977        enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3978
3979        synchronized (this) {
3980            int targetUser = getProfileParentId(userHandle);
3981            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3982            return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3983        }
3984    }
3985
3986    private boolean isActivePasswordSufficientForUserLocked(
3987            DevicePolicyData policy, int userHandle, boolean parent) {
3988        enforceUserUnlocked(userHandle, parent);
3989
3990        final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
3991        if (policy.mActivePasswordMetrics.quality < requiredPasswordQuality) {
3992            return false;
3993        }
3994        if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
3995                && policy.mActivePasswordMetrics.length < getPasswordMinimumLength(
3996                        null, userHandle, parent)) {
3997            return false;
3998        }
3999        if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4000            return true;
4001        }
4002        return policy.mActivePasswordMetrics.upperCase >= getPasswordMinimumUpperCase(
4003                    null, userHandle, parent)
4004                && policy.mActivePasswordMetrics.lowerCase >= getPasswordMinimumLowerCase(
4005                        null, userHandle, parent)
4006                && policy.mActivePasswordMetrics.letters >= getPasswordMinimumLetters(
4007                        null, userHandle, parent)
4008                && policy.mActivePasswordMetrics.numeric >= getPasswordMinimumNumeric(
4009                        null, userHandle, parent)
4010                && policy.mActivePasswordMetrics.symbols >= getPasswordMinimumSymbols(
4011                        null, userHandle, parent)
4012                && policy.mActivePasswordMetrics.nonLetter >= getPasswordMinimumNonLetter(
4013                        null, userHandle, parent);
4014    }
4015
4016    @Override
4017    public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
4018        enforceFullCrossUsersPermission(userHandle);
4019        synchronized (this) {
4020            if (!isCallerWithSystemUid()) {
4021                // This API can only be called by an active device admin,
4022                // so try to retrieve it to check that the caller is one.
4023                getActiveAdminForCallerLocked(
4024                        null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4025            }
4026
4027            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4028
4029            return policy.mFailedPasswordAttempts;
4030        }
4031    }
4032
4033    @Override
4034    public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
4035        if (!mHasFeature) {
4036            return;
4037        }
4038        Preconditions.checkNotNull(who, "ComponentName is null");
4039        synchronized (this) {
4040            // This API can only be called by an active device admin,
4041            // so try to retrieve it to check that the caller is one.
4042            getActiveAdminForCallerLocked(
4043                    who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
4044            ActiveAdmin ap = getActiveAdminForCallerLocked(
4045                    who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4046            if (ap.maximumFailedPasswordsForWipe != num) {
4047                ap.maximumFailedPasswordsForWipe = num;
4048                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4049            }
4050        }
4051    }
4052
4053    @Override
4054    public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
4055        if (!mHasFeature) {
4056            return 0;
4057        }
4058        enforceFullCrossUsersPermission(userHandle);
4059        synchronized (this) {
4060            ActiveAdmin admin = (who != null)
4061                    ? getActiveAdminUncheckedLocked(who, userHandle, parent)
4062                    : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
4063            return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
4064        }
4065    }
4066
4067    @Override
4068    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
4069        if (!mHasFeature) {
4070            return UserHandle.USER_NULL;
4071        }
4072        enforceFullCrossUsersPermission(userHandle);
4073        synchronized (this) {
4074            ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4075                    userHandle, parent);
4076            return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
4077        }
4078    }
4079
4080    /**
4081     * Returns the admin with the strictest policy on maximum failed passwords for:
4082     * <ul>
4083     *   <li>this user if it has a separate profile challenge, or
4084     *   <li>this user and all profiles that don't have their own challenge otherwise.
4085     * </ul>
4086     * <p>If the policy for the primary and any other profile are equal, it returns the admin for
4087     * the primary profile.
4088     * Returns {@code null} if no participating admin has that policy set.
4089     */
4090    private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
4091            int userHandle, boolean parent) {
4092        int count = 0;
4093        ActiveAdmin strictestAdmin = null;
4094
4095        // Return the strictest policy across all participating admins.
4096        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4097        final int N = admins.size();
4098        for (int i = 0; i < N; i++) {
4099            ActiveAdmin admin = admins.get(i);
4100            if (admin.maximumFailedPasswordsForWipe ==
4101                    ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
4102                continue;  // No max number of failed passwords policy set for this profile.
4103            }
4104
4105            // We always favor the primary profile if several profiles have the same value set.
4106            int userId = admin.getUserHandle().getIdentifier();
4107            if (count == 0 ||
4108                    count > admin.maximumFailedPasswordsForWipe ||
4109                    (count == admin.maximumFailedPasswordsForWipe &&
4110                            getUserInfo(userId).isPrimary())) {
4111                count = admin.maximumFailedPasswordsForWipe;
4112                strictestAdmin = admin;
4113            }
4114        }
4115        return strictestAdmin;
4116    }
4117
4118    private UserInfo getUserInfo(@UserIdInt int userId) {
4119        final long token = mInjector.binderClearCallingIdentity();
4120        try {
4121            return mUserManager.getUserInfo(userId);
4122        } finally {
4123            mInjector.binderRestoreCallingIdentity(token);
4124        }
4125    }
4126
4127    @Override
4128    public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
4129        if (!mHasFeature) {
4130            return false;
4131        }
4132        final int callingUid = mInjector.binderGetCallingUid();
4133        final int userHandle = mInjector.userHandleGetCallingUserId();
4134
4135        String password = passwordOrNull != null ? passwordOrNull : "";
4136
4137        // Password resetting to empty/null is not allowed for managed profiles.
4138        if (TextUtils.isEmpty(password)) {
4139            enforceNotManagedProfile(userHandle, "clear the active password");
4140        }
4141
4142        int quality;
4143        synchronized (this) {
4144            // If caller has PO (or DO) it can change the password, so see if that's the case first.
4145            ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
4146                    null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
4147            final boolean preN;
4148            if (admin != null) {
4149                preN = getTargetSdk(admin.info.getPackageName(),
4150                        userHandle) <= android.os.Build.VERSION_CODES.M;
4151            } else {
4152                // Otherwise, make sure the caller has any active admin with the right policy.
4153                admin = getActiveAdminForCallerLocked(null,
4154                        DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
4155                preN = getTargetSdk(admin.info.getPackageName(),
4156                        userHandle) <= android.os.Build.VERSION_CODES.M;
4157
4158                // As of N, password resetting to empty/null is not allowed anymore.
4159                // TODO Should we allow DO/PO to set an empty password?
4160                if (TextUtils.isEmpty(password)) {
4161                    if (!preN) {
4162                        throw new SecurityException("Cannot call with null password");
4163                    } else {
4164                        Slog.e(LOG_TAG, "Cannot call with null password");
4165                        return false;
4166                    }
4167                }
4168                // As of N, password cannot be changed by the admin if it is already set.
4169                if (isLockScreenSecureUnchecked(userHandle)) {
4170                    if (!preN) {
4171                        throw new SecurityException("Admin cannot change current password");
4172                    } else {
4173                        Slog.e(LOG_TAG, "Admin cannot change current password");
4174                        return false;
4175                    }
4176                }
4177            }
4178            // Do not allow to reset password when current user has a managed profile
4179            if (!isManagedProfile(userHandle)) {
4180                for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4181                    if (userInfo.isManagedProfile()) {
4182                        if (!preN) {
4183                            throw new IllegalStateException(
4184                                    "Cannot reset password on user has managed profile");
4185                        } else {
4186                            Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
4187                            return false;
4188                        }
4189                    }
4190                }
4191            }
4192            // Do not allow to reset password when user is locked
4193            if (!mUserManager.isUserUnlocked(userHandle)) {
4194                if (!preN) {
4195                    throw new IllegalStateException("Cannot reset password when user is locked");
4196                } else {
4197                    Slog.e(LOG_TAG, "Cannot reset password when user is locked");
4198                    return false;
4199                }
4200            }
4201
4202            quality = getPasswordQuality(null, userHandle, /* parent */ false);
4203            if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
4204                quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4205            }
4206            final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password);
4207            if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
4208                final int realQuality = metrics.quality;
4209                if (realQuality < quality
4210                        && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4211                    Slog.w(LOG_TAG, "resetPassword: password quality 0x"
4212                            + Integer.toHexString(realQuality)
4213                            + " does not meet required quality 0x"
4214                            + Integer.toHexString(quality));
4215                    return false;
4216                }
4217                quality = Math.max(realQuality, quality);
4218            }
4219            int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
4220            if (password.length() < length) {
4221                Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
4222                        + " does not meet required length " + length);
4223                return false;
4224            }
4225            if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4226                int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4227                if(metrics.letters < neededLetters) {
4228                    Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters
4229                            + " does not meet required number of letters " + neededLetters);
4230                    return false;
4231                }
4232                int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4233                if (metrics.numeric < neededNumeric) {
4234                    Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric
4235                            + " does not meet required number of numerical digits "
4236                            + neededNumeric);
4237                    return false;
4238                }
4239                int neededLowerCase = getPasswordMinimumLowerCase(
4240                        null, userHandle, /* parent */ false);
4241                if (metrics.lowerCase < neededLowerCase) {
4242                    Slog.w(LOG_TAG, "resetPassword: number of lowercase letters "
4243                            + metrics.lowerCase
4244                            + " does not meet required number of lowercase letters "
4245                            + neededLowerCase);
4246                    return false;
4247                }
4248                int neededUpperCase = getPasswordMinimumUpperCase(
4249                        null, userHandle, /* parent */ false);
4250                if (metrics.upperCase < neededUpperCase) {
4251                    Slog.w(LOG_TAG, "resetPassword: number of uppercase letters "
4252                            + metrics.upperCase
4253                            + " does not meet required number of uppercase letters "
4254                            + neededUpperCase);
4255                    return false;
4256                }
4257                int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4258                if (metrics.symbols < neededSymbols) {
4259                    Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols
4260                            + " does not meet required number of special symbols " + neededSymbols);
4261                    return false;
4262                }
4263                int neededNonLetter = getPasswordMinimumNonLetter(
4264                        null, userHandle, /* parent */ false);
4265                if (metrics.nonLetter < neededNonLetter) {
4266                    Slog.w(LOG_TAG, "resetPassword: number of non-letter characters "
4267                            + metrics.nonLetter
4268                            + " does not meet required number of non-letter characters "
4269                            + neededNonLetter);
4270                    return false;
4271                }
4272            }
4273        }
4274
4275        DevicePolicyData policy = getUserData(userHandle);
4276        if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4277            Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4278            return false;
4279        }
4280
4281        boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4282        boolean doNotAskCredentialsOnBoot =
4283                (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4284        if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4285            setDoNotAskCredentialsOnBoot();
4286        }
4287
4288        // Don't do this with the lock held, because it is going to call
4289        // back in to the service.
4290        final long ident = mInjector.binderClearCallingIdentity();
4291        try {
4292            if (!TextUtils.isEmpty(password)) {
4293                mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4294            } else {
4295                mLockPatternUtils.clearLock(userHandle);
4296            }
4297            boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4298            if (requireEntry) {
4299                mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4300                        UserHandle.USER_ALL);
4301            }
4302            synchronized (this) {
4303                int newOwner = requireEntry ? callingUid : -1;
4304                if (policy.mPasswordOwner != newOwner) {
4305                    policy.mPasswordOwner = newOwner;
4306                    saveSettingsLocked(userHandle);
4307                }
4308            }
4309        } finally {
4310            mInjector.binderRestoreCallingIdentity(ident);
4311        }
4312
4313        return true;
4314    }
4315
4316    private boolean isLockScreenSecureUnchecked(int userId) {
4317        long ident = mInjector.binderClearCallingIdentity();
4318        try {
4319            return mLockPatternUtils.isSecure(userId);
4320        } finally {
4321            mInjector.binderRestoreCallingIdentity(ident);
4322        }
4323    }
4324
4325    private void setDoNotAskCredentialsOnBoot() {
4326        synchronized (this) {
4327            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4328            if (!policyData.doNotAskCredentialsOnBoot) {
4329                policyData.doNotAskCredentialsOnBoot = true;
4330                saveSettingsLocked(UserHandle.USER_SYSTEM);
4331            }
4332        }
4333    }
4334
4335    @Override
4336    public boolean getDoNotAskCredentialsOnBoot() {
4337        mContext.enforceCallingOrSelfPermission(
4338                android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4339        synchronized (this) {
4340            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4341            return policyData.doNotAskCredentialsOnBoot;
4342        }
4343    }
4344
4345    @Override
4346    public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4347        if (!mHasFeature) {
4348            return;
4349        }
4350        Preconditions.checkNotNull(who, "ComponentName is null");
4351        final int userHandle = mInjector.userHandleGetCallingUserId();
4352        synchronized (this) {
4353            ActiveAdmin ap = getActiveAdminForCallerLocked(
4354                    who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4355            if (ap.maximumTimeToUnlock != timeMs) {
4356                ap.maximumTimeToUnlock = timeMs;
4357                saveSettingsLocked(userHandle);
4358                updateMaximumTimeToLockLocked(userHandle);
4359            }
4360        }
4361    }
4362
4363    void updateMaximumTimeToLockLocked(int userHandle) {
4364        // Calculate the min timeout for all profiles - including the ones with a separate
4365        // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4366        // challenge only and keep the screen on. However there is no easy way of doing that at the
4367        // moment so we set the screen off timeout regardless of whether it affects the parent user
4368        // or the profile challenge only.
4369        long timeMs = Long.MAX_VALUE;
4370        int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4371        for (int profileId : profileIds) {
4372            DevicePolicyData policy = getUserDataUnchecked(profileId);
4373            final int N = policy.mAdminList.size();
4374            for (int i = 0; i < N; i++) {
4375                ActiveAdmin admin = policy.mAdminList.get(i);
4376                if (admin.maximumTimeToUnlock > 0
4377                        && timeMs > admin.maximumTimeToUnlock) {
4378                    timeMs = admin.maximumTimeToUnlock;
4379                }
4380                // If userInfo.id is a managed profile, we also need to look at
4381                // the policies set on the parent.
4382                if (admin.hasParentActiveAdmin()) {
4383                    final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4384                    if (parentAdmin.maximumTimeToUnlock > 0
4385                            && timeMs > parentAdmin.maximumTimeToUnlock) {
4386                        timeMs = parentAdmin.maximumTimeToUnlock;
4387                    }
4388                }
4389            }
4390        }
4391
4392        // We only store the last maximum time to lock on the parent profile. So if calling from a
4393        // managed profile, retrieve the policy for the parent.
4394        DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4395        if (policy.mLastMaximumTimeToLock == timeMs) {
4396            return;
4397        }
4398        policy.mLastMaximumTimeToLock = timeMs;
4399
4400        final long ident = mInjector.binderClearCallingIdentity();
4401        try {
4402            if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4403                // Make sure KEEP_SCREEN_ON is disabled, since that
4404                // would allow bypassing of the maximum time to lock.
4405                mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4406            }
4407
4408            mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4409                    (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4410        } finally {
4411            mInjector.binderRestoreCallingIdentity(ident);
4412        }
4413    }
4414
4415    @Override
4416    public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4417        if (!mHasFeature) {
4418            return 0;
4419        }
4420        enforceFullCrossUsersPermission(userHandle);
4421        synchronized (this) {
4422            if (who != null) {
4423                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4424                return admin != null ? admin.maximumTimeToUnlock : 0;
4425            }
4426            // Return the strictest policy across all participating admins.
4427            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4428                    userHandle, parent);
4429            return getMaximumTimeToLockPolicyFromAdmins(admins);
4430        }
4431    }
4432
4433    @Override
4434    public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4435        if (!mHasFeature) {
4436            return 0;
4437        }
4438        enforceFullCrossUsersPermission(userHandle);
4439        synchronized (this) {
4440            // All admins for this user.
4441            ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4442            for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4443                DevicePolicyData policy = getUserData(userInfo.id);
4444                admins.addAll(policy.mAdminList);
4445                // If it is a managed profile, it may have parent active admins
4446                if (userInfo.isManagedProfile()) {
4447                    for (ActiveAdmin admin : policy.mAdminList) {
4448                        if (admin.hasParentActiveAdmin()) {
4449                            admins.add(admin.getParentActiveAdmin());
4450                        }
4451                    }
4452                }
4453            }
4454            return getMaximumTimeToLockPolicyFromAdmins(admins);
4455        }
4456    }
4457
4458    private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4459        long time = 0;
4460        final int N = admins.size();
4461        for (int i = 0; i < N; i++) {
4462            ActiveAdmin admin = admins.get(i);
4463            if (time == 0) {
4464                time = admin.maximumTimeToUnlock;
4465            } else if (admin.maximumTimeToUnlock != 0
4466                    && time > admin.maximumTimeToUnlock) {
4467                time = admin.maximumTimeToUnlock;
4468            }
4469        }
4470        return time;
4471    }
4472
4473    @Override
4474    public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
4475            boolean parent) {
4476        if (!mHasFeature) {
4477            return;
4478        }
4479        Preconditions.checkNotNull(who, "ComponentName is null");
4480        Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
4481        // timeoutMs with value 0 means that the admin doesn't participate
4482        // timeoutMs is clamped to the interval in case the internal constants change in the future
4483        final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
4484        if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
4485            timeoutMs = minimumStrongAuthTimeout;
4486        }
4487        if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
4488            timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4489        }
4490
4491        final int userHandle = mInjector.userHandleGetCallingUserId();
4492        synchronized (this) {
4493            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4494                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4495            if (ap.strongAuthUnlockTimeout != timeoutMs) {
4496                ap.strongAuthUnlockTimeout = timeoutMs;
4497                saveSettingsLocked(userHandle);
4498            }
4499        }
4500    }
4501
4502    /**
4503     * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
4504     * admins if who is null.
4505     * Returns 0 if not configured for the provided admin.
4506     */
4507    @Override
4508    public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
4509        if (!mHasFeature) {
4510            return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4511        }
4512        enforceFullCrossUsersPermission(userId);
4513        synchronized (this) {
4514            if (who != null) {
4515                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
4516                return admin != null ? admin.strongAuthUnlockTimeout : 0;
4517            }
4518
4519            // Return the strictest policy across all participating admins.
4520            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
4521
4522            long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4523            for (int i = 0; i < admins.size(); i++) {
4524                final long timeout = admins.get(i).strongAuthUnlockTimeout;
4525                if (timeout != 0) { // take only participating admins into account
4526                    strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
4527                }
4528            }
4529            return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
4530        }
4531    }
4532
4533    private long getMinimumStrongAuthTimeoutMs() {
4534        if (!mInjector.isBuildDebuggable()) {
4535            return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
4536        }
4537        // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
4538        // name cannot be longer than 31 characters
4539        return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
4540                MINIMUM_STRONG_AUTH_TIMEOUT_MS),
4541                MINIMUM_STRONG_AUTH_TIMEOUT_MS);
4542    }
4543
4544    @Override
4545    public void lockNow(int flags, boolean parent) {
4546        if (!mHasFeature) {
4547            return;
4548        }
4549
4550        final int callingUserId = mInjector.userHandleGetCallingUserId();
4551        synchronized (this) {
4552            // This API can only be called by an active device admin,
4553            // so try to retrieve it to check that the caller is one.
4554            final ActiveAdmin admin = getActiveAdminForCallerLocked(
4555                    null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4556
4557            final long ident = mInjector.binderClearCallingIdentity();
4558            try {
4559                // Evict key
4560                if ((flags & DevicePolicyManager.FLAG_EVICT_CE_KEY) != 0) {
4561                    enforceManagedProfile(callingUserId, "set FLAG_EVICT_CE_KEY");
4562                    if (!isProfileOwner(admin.info.getComponent(), callingUserId)) {
4563                        throw new SecurityException(
4564                               "Only profile owner admins can set FLAG_EVICT_CE_KEY");
4565                    }
4566                    if (parent) {
4567                        throw new IllegalArgumentException(
4568                                "Cannot set FLAG_EVICT_CE_KEY for the parent");
4569                    }
4570                    if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
4571                        throw new UnsupportedOperationException(
4572                                "FLAG_EVICT_CE_KEY only applies to FBE devices");
4573                    }
4574                    mUserManager.evictCredentialEncryptionKey(callingUserId);
4575                }
4576
4577                // Lock all users unless this is a managed profile with a separate challenge
4578                final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
4579                        ? UserHandle.USER_ALL : callingUserId);
4580                mLockPatternUtils.requireStrongAuth(
4581                        STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4582
4583                // Require authentication for the device or profile
4584                if (userToLock == UserHandle.USER_ALL) {
4585                    // Power off the display
4586                    mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4587                            PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4588                    mInjector.getIWindowManager().lockNow(null);
4589                } else {
4590                    mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4591                }
4592            } catch (RemoteException e) {
4593            } finally {
4594                mInjector.binderRestoreCallingIdentity(ident);
4595            }
4596        }
4597    }
4598
4599    @Override
4600    public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
4601        if (who == null) {
4602            if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) {
4603                mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4604            }
4605        } else {
4606            enforceProfileOrDeviceOwner(who);
4607        }
4608    }
4609
4610    private void enforceProfileOrDeviceOwner(ComponentName who) {
4611        synchronized (this) {
4612            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4613        }
4614    }
4615
4616    @Override
4617    public boolean approveCaCert(String alias, int userId, boolean approval) {
4618        enforceManageUsers();
4619        synchronized (this) {
4620            Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4621            boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4622            if (!changed) {
4623                return false;
4624            }
4625            saveSettingsLocked(userId);
4626        }
4627        new MonitoringCertNotificationTask().execute(userId);
4628        return true;
4629    }
4630
4631    @Override
4632    public boolean isCaCertApproved(String alias, int userId) {
4633        enforceManageUsers();
4634        synchronized (this) {
4635            return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4636        }
4637    }
4638
4639    private void removeCaApprovalsIfNeeded(int userId) {
4640        for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4641            boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4642            if (userInfo.isManagedProfile()){
4643                isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4644            }
4645            if (!isSecure) {
4646                synchronized (this) {
4647                    getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4648                    saveSettingsLocked(userInfo.id);
4649                }
4650
4651                new MonitoringCertNotificationTask().execute(userInfo.id);
4652            }
4653        }
4654    }
4655
4656    @Override
4657    public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)
4658            throws RemoteException {
4659        enforceCanManageCaCerts(admin, callerPackage);
4660
4661        byte[] pemCert;
4662        try {
4663            X509Certificate cert = parseCert(certBuffer);
4664            pemCert = Credentials.convertToPem(cert);
4665        } catch (CertificateException ce) {
4666            Log.e(LOG_TAG, "Problem converting cert", ce);
4667            return false;
4668        } catch (IOException ioe) {
4669            Log.e(LOG_TAG, "Problem reading cert", ioe);
4670            return false;
4671        }
4672
4673        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4674        final long id = mInjector.binderClearCallingIdentity();
4675        try {
4676            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4677            try {
4678                keyChainConnection.getService().installCaCertificate(pemCert);
4679                return true;
4680            } catch (RemoteException e) {
4681                Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4682            } finally {
4683                keyChainConnection.close();
4684            }
4685        } catch (InterruptedException e1) {
4686            Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4687            Thread.currentThread().interrupt();
4688        } finally {
4689            mInjector.binderRestoreCallingIdentity(id);
4690        }
4691        return false;
4692    }
4693
4694    private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4695        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4696        return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4697                certBuffer));
4698    }
4699
4700    @Override
4701    public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
4702        enforceCanManageCaCerts(admin, callerPackage);
4703
4704        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4705        final long id = mInjector.binderClearCallingIdentity();
4706        try {
4707            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4708            try {
4709                for (int i = 0 ; i < aliases.length; i++) {
4710                    keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4711                }
4712            } catch (RemoteException e) {
4713                Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4714            } finally {
4715                keyChainConnection.close();
4716            }
4717        } catch (InterruptedException ie) {
4718            Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4719            Thread.currentThread().interrupt();
4720        } finally {
4721            mInjector.binderRestoreCallingIdentity(id);
4722        }
4723    }
4724
4725    @Override
4726    public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
4727            byte[] cert, byte[] chain, String alias, boolean requestAccess) {
4728        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
4729                DELEGATION_CERT_INSTALL);
4730
4731
4732        final int callingUid = mInjector.binderGetCallingUid();
4733        final long id = mInjector.binderClearCallingIdentity();
4734        try {
4735            final KeyChainConnection keyChainConnection =
4736                    KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4737            try {
4738                IKeyChainService keyChain = keyChainConnection.getService();
4739                if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4740                    return false;
4741                }
4742                if (requestAccess) {
4743                    keyChain.setGrant(callingUid, alias, true);
4744                }
4745                return true;
4746            } catch (RemoteException e) {
4747                Log.e(LOG_TAG, "Installing certificate", e);
4748            } finally {
4749                keyChainConnection.close();
4750            }
4751        } catch (InterruptedException e) {
4752            Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4753            Thread.currentThread().interrupt();
4754        } finally {
4755            mInjector.binderRestoreCallingIdentity(id);
4756        }
4757        return false;
4758    }
4759
4760    @Override
4761    public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
4762        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
4763                DELEGATION_CERT_INSTALL);
4764
4765        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4766        final long id = Binder.clearCallingIdentity();
4767        try {
4768            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4769            try {
4770                IKeyChainService keyChain = keyChainConnection.getService();
4771                return keyChain.removeKeyPair(alias);
4772            } catch (RemoteException e) {
4773                Log.e(LOG_TAG, "Removing keypair", e);
4774            } finally {
4775                keyChainConnection.close();
4776            }
4777        } catch (InterruptedException e) {
4778            Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4779            Thread.currentThread().interrupt();
4780        } finally {
4781            Binder.restoreCallingIdentity(id);
4782        }
4783        return false;
4784    }
4785
4786    @Override
4787    public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4788            final IBinder response) {
4789        // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4790        if (!isCallerWithSystemUid()) {
4791            return;
4792        }
4793
4794        final UserHandle caller = mInjector.binderGetCallingUserHandle();
4795        // If there is a profile owner, redirect to that; otherwise query the device owner.
4796        ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4797        if (aliasChooser == null && caller.isSystem()) {
4798            ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4799            if (deviceOwnerAdmin != null) {
4800                aliasChooser = deviceOwnerAdmin.info.getComponent();
4801            }
4802        }
4803        if (aliasChooser == null) {
4804            sendPrivateKeyAliasResponse(null, response);
4805            return;
4806        }
4807
4808        Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4809        intent.setComponent(aliasChooser);
4810        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4811        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4812        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4813        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4814        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4815
4816        final long id = mInjector.binderClearCallingIdentity();
4817        try {
4818            mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4819                @Override
4820                public void onReceive(Context context, Intent intent) {
4821                    final String chosenAlias = getResultData();
4822                    sendPrivateKeyAliasResponse(chosenAlias, response);
4823                }
4824            }, null, Activity.RESULT_OK, null, null);
4825        } finally {
4826            mInjector.binderRestoreCallingIdentity(id);
4827        }
4828    }
4829
4830    private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4831        final IKeyChainAliasCallback keyChainAliasResponse =
4832                IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4833        new AsyncTask<Void, Void, Void>() {
4834            @Override
4835            protected Void doInBackground(Void... unused) {
4836                try {
4837                    keyChainAliasResponse.alias(alias);
4838                } catch (Exception e) {
4839                    // Catch everything (not just RemoteException): caller could throw a
4840                    // RuntimeException back across processes.
4841                    Log.e(LOG_TAG, "error while responding to callback", e);
4842                }
4843                return null;
4844            }
4845        }.execute();
4846    }
4847
4848    /**
4849     * Set the scopes of a device owner or profile owner delegate.
4850     *
4851     * @param who the device owner or profile owner.
4852     * @param delegatePackage the name of the delegate package.
4853     * @param scopes the list of delegation scopes to be given to the delegate package.
4854     */
4855    @Override
4856    public void setDelegatedScopes(ComponentName who, String delegatePackage,
4857            List<String> scopes) throws SecurityException {
4858        Preconditions.checkNotNull(who, "ComponentName is null");
4859        Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
4860        Preconditions.checkCollectionElementsNotNull(scopes, "Scopes");
4861        // Remove possible duplicates.
4862        scopes = new ArrayList(new ArraySet(scopes));
4863        // Ensure given scopes are valid.
4864        if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
4865            throw new IllegalArgumentException("Unexpected delegation scopes");
4866        }
4867
4868        // Retrieve the user ID of the calling process.
4869        final int userId = mInjector.userHandleGetCallingUserId();
4870        synchronized (this) {
4871            // Ensure calling process is device/profile owner.
4872            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4873            // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
4874            if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL) ||
4875                    getTargetSdk(who.getPackageName(), userId) >= Build.VERSION_CODES.N) {
4876                // Throw when the delegate package is not installed.
4877                if (!isPackageInstalledForUser(delegatePackage, userId)) {
4878                    throw new IllegalArgumentException("Package " + delegatePackage
4879                            + " is not installed on the current user");
4880                }
4881            }
4882
4883            // Set the new delegate in user policies.
4884            final DevicePolicyData policy = getUserData(userId);
4885            if (!scopes.isEmpty()) {
4886                policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
4887            } else {
4888                // Remove any delegation info if the given scopes list is empty.
4889                policy.mDelegationMap.remove(delegatePackage);
4890            }
4891
4892            // Notify delegate package of updates.
4893            final Intent intent = new Intent(
4894                    DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
4895            // Only call receivers registered in the manifest (don’t wake app if not running).
4896            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4897            // Limit components this intent resolves to to the delegate package.
4898            intent.setPackage(delegatePackage);
4899            // Include the list of delegated scopes as an extra.
4900            intent.putExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, scopes.toArray());
4901            // Send the broadcast.
4902            mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4903
4904            // Persist updates.
4905            saveSettingsLocked(userId);
4906        }
4907    }
4908
4909    /**
4910     * Get the delegation scopes given to a delegate package by a device owner or profile owner.
4911     *
4912     * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
4913     * passing in {@code null} as the {@code who} parameter and its own name as the
4914     * {@code delegatepackage}.
4915     *
4916     * @param who the device owner or profile owner, or {@code null} if the caller is
4917     *            {@code delegatePackage}.
4918     * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
4919     * @return a list of the delegation scopes currently given to {@code delegatePackage}.
4920     */
4921    @Override
4922    @NonNull
4923    public List<String> getDelegatedScopes(ComponentName who,
4924            String delegatePackage) throws SecurityException {
4925        Preconditions.checkNotNull(delegatePackage, "Delegate package is null");
4926
4927        // Retrieve the user ID of the calling process.
4928        final int callingUid = mInjector.binderGetCallingUid();
4929        final int userId = UserHandle.getUserId(callingUid);
4930        synchronized (this) {
4931            // Ensure calling process is device/profile owner.
4932            if (who != null) {
4933                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4934            // Or ensure calling process is delegatePackage itself.
4935            } else {
4936                int uid = 0;
4937                try {
4938                  uid = mInjector.getPackageManager()
4939                          .getPackageUidAsUser(delegatePackage, userId);
4940                } catch(NameNotFoundException e) {
4941                }
4942                if (uid != callingUid) {
4943                    throw new SecurityException("Caller with uid " + callingUid + " is not "
4944                            + delegatePackage);
4945                }
4946            }
4947            final DevicePolicyData policy = getUserData(userId);
4948            // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
4949            final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
4950            return scopes == null ? Collections.EMPTY_LIST : scopes;
4951        }
4952    }
4953
4954    /**
4955     * Get a list of  packages that were given a specific delegation scopes by a device owner or
4956     * profile owner.
4957     *
4958     * @param who the device owner or profile owner.
4959     * @param scope the scope whose delegates are to be retrieved.
4960     * @return a list of the delegate packages currently given the {@code scope} delegation.
4961     */
4962    @NonNull
4963    public List<String> getDelegatePackages(ComponentName who, String scope)
4964            throws SecurityException {
4965        Preconditions.checkNotNull(who, "ComponentName is null");
4966        Preconditions.checkNotNull(scope, "Scope is null");
4967        if (!Arrays.asList(DELEGATIONS).contains(scope)) {
4968            throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
4969        }
4970
4971        // Retrieve the user ID of the calling process.
4972        final int userId = mInjector.userHandleGetCallingUserId();
4973        synchronized (this) {
4974            // Ensure calling process is device/profile owner.
4975            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4976            final DevicePolicyData policy = getUserData(userId);
4977
4978            // Create a list to hold the resulting delegate packages.
4979            final List<String> delegatePackagesWithScope = new ArrayList<>();
4980            // Add all delegations containing scope to the result list.
4981            for (int i = 0; i < policy.mDelegationMap.size(); i++) {
4982                if (policy.mDelegationMap.valueAt(i).contains(scope)) {
4983                    delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
4984                }
4985            }
4986            return delegatePackagesWithScope;
4987        }
4988    }
4989
4990    /**
4991     * Check whether a caller application has been delegated a given scope via
4992     * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
4993     * device owner.
4994     * <p>
4995     * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
4996     * then comparing the calling UID with the UID of {@code callerPackage} as reported by
4997     * {@link PackageManager#getPackageUidAsUser}.
4998     *
4999     * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
5000     * @param scope the delegation scope to be checked.
5001     * @return {@code true} if the calling process is a delegate of {@code scope}.
5002     */
5003    private boolean isCallerDelegate(String callerPackage, String scope) {
5004        Preconditions.checkNotNull(callerPackage, "callerPackage is null");
5005        if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5006            throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5007        }
5008
5009        // Retrieve the UID and user ID of the calling process.
5010        final int callingUid = mInjector.binderGetCallingUid();
5011        final int userId = UserHandle.getUserId(callingUid);
5012        synchronized (this) {
5013            // Retrieve user policy data.
5014            final DevicePolicyData policy = getUserData(userId);
5015            // Retrieve the list of delegation scopes granted to callerPackage.
5016            final List<String> scopes = policy.mDelegationMap.get(callerPackage);
5017            // Check callingUid only if callerPackage has the required scope delegation.
5018            if (scopes != null && scopes.contains(scope)) {
5019                try {
5020                    // Retrieve the expected UID for callerPackage.
5021                    final int uid = mInjector.getPackageManager()
5022                            .getPackageUidAsUser(callerPackage, userId);
5023                    // Return true if the caller is actually callerPackage.
5024                    return uid == callingUid;
5025                } catch (NameNotFoundException e) {
5026                    // Ignore.
5027                }
5028            }
5029            return false;
5030        }
5031    }
5032
5033    /**
5034     * Throw a security exception if a ComponentName is given and it is not a device/profile owner
5035     * or if the calling process is not a delegate of the given scope.
5036     *
5037     * @param who the device owner of profile owner, or null if {@code callerPackage} is a
5038     *            {@code scope} delegate.
5039     * @param callerPackage the name of the calling package. Required if {@code who} is
5040     *            {@code null}.
5041     * @param reqPolicy the policy used in the API whose access permission is being checked.
5042     * @param scoppe the delegation scope corresponding to the API being checked.
5043     * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy};
5044     *            or when {@code who} is {@code null} and {@code callerPackage} is not a delegate
5045     *            of {@code scope}.
5046     */
5047    private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy,
5048            String scope) {
5049        // If a ComponentName is given ensure it is a device or profile owner according to policy.
5050        if (who != null) {
5051            synchronized (this) {
5052                getActiveAdminForCallerLocked(who, reqPolicy);
5053            }
5054        // If no ComponentName is given ensure calling process has scope delegation.
5055        } else if (!isCallerDelegate(callerPackage, scope)) {
5056            throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid()
5057                    + " is not a delegate of scope " + scope + ".");
5058        }
5059    }
5060
5061    /**
5062     * Helper function to preserve delegation behavior pre-O when using the deprecated functions
5063     * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
5064     */
5065    private void setDelegatedScopePreO(ComponentName who,
5066            String delegatePackage, String scope) {
5067        Preconditions.checkNotNull(who, "ComponentName is null");
5068
5069        final int userId = mInjector.userHandleGetCallingUserId();
5070        synchronized(this) {
5071            // Ensure calling process is device/profile owner.
5072            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5073            final DevicePolicyData policy = getUserData(userId);
5074
5075            if (delegatePackage != null) {
5076                // Set package as a delegate for scope if it is not already one.
5077                List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5078                if (scopes == null) {
5079                    scopes = new ArrayList<>();
5080                }
5081                if (!scopes.contains(scope)) {
5082                    scopes.add(scope);
5083                    setDelegatedScopes(who, delegatePackage, scopes);
5084                }
5085            }
5086
5087            // Clear any existing scope delegates.
5088            for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5089                final String currentPackage = policy.mDelegationMap.keyAt(i);
5090                final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
5091
5092                if (!currentPackage.equals(delegatePackage) && currentScopes.remove(scope)) {
5093                    setDelegatedScopes(who, currentPackage, currentScopes);
5094                }
5095            }
5096        }
5097    }
5098
5099    @Override
5100    public void setCertInstallerPackage(ComponentName who, String installerPackage)
5101            throws SecurityException {
5102        setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
5103    }
5104
5105    @Override
5106    public String getCertInstallerPackage(ComponentName who) throws SecurityException {
5107        final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
5108        return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
5109    }
5110
5111    /**
5112     * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
5113     * not installed and therefore not available.
5114     *
5115     * @throws SecurityException if the caller is not a profile or device owner.
5116     * @throws UnsupportedOperationException if the package does not support being set as always-on.
5117     */
5118    @Override
5119    public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
5120            throws SecurityException {
5121        enforceProfileOrDeviceOwner(admin);
5122
5123        final int userId = mInjector.userHandleGetCallingUserId();
5124        final long token = mInjector.binderClearCallingIdentity();
5125        try {
5126            if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
5127                return false;
5128            }
5129            ConnectivityManager connectivityManager = (ConnectivityManager)
5130                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5131            if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
5132                throw new UnsupportedOperationException();
5133            }
5134        } finally {
5135            mInjector.binderRestoreCallingIdentity(token);
5136        }
5137        return true;
5138    }
5139
5140    @Override
5141    public String getAlwaysOnVpnPackage(ComponentName admin)
5142            throws SecurityException {
5143        enforceProfileOrDeviceOwner(admin);
5144
5145        final int userId = mInjector.userHandleGetCallingUserId();
5146        final long token = mInjector.binderClearCallingIdentity();
5147        try{
5148            ConnectivityManager connectivityManager = (ConnectivityManager)
5149                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5150            return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
5151        } finally {
5152            mInjector.binderRestoreCallingIdentity(token);
5153        }
5154    }
5155
5156    private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason) {
5157        wtfIfInLock();
5158
5159        if (wipeExtRequested) {
5160            StorageManager sm = (StorageManager) mContext.getSystemService(
5161                    Context.STORAGE_SERVICE);
5162            sm.wipeAdoptableDisks();
5163        }
5164        try {
5165            mInjector.recoverySystemRebootWipeUserData(
5166                    /*shutdown=*/ false, reason, /*force=*/ true);
5167        } catch (IOException | SecurityException e) {
5168            Slog.w(LOG_TAG, "Failed requesting data wipe", e);
5169        }
5170    }
5171
5172    private void forceWipeUser(int userId) {
5173        try {
5174            IActivityManager am = mInjector.getIActivityManager();
5175            if (am.getCurrentUser().id == userId) {
5176                am.switchUser(UserHandle.USER_SYSTEM);
5177            }
5178
5179            boolean userRemoved = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
5180            if (!userRemoved) {
5181                Slog.w(LOG_TAG, "Couldn't remove user " + userId);
5182            } else if (isManagedProfile(userId)) {
5183                sendWipeProfileNotification();
5184            }
5185        } catch (RemoteException re) {
5186            // Shouldn't happen
5187        }
5188    }
5189
5190    @Override
5191    public void wipeData(int flags) {
5192        if (!mHasFeature) {
5193            return;
5194        }
5195        enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId());
5196
5197        final ActiveAdmin admin;
5198        synchronized (this) {
5199            admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA);
5200        }
5201        String reason = "DevicePolicyManager.wipeData() from "
5202                + admin.info.getComponent().flattenToShortString();
5203        wipeDataNoLock(
5204                admin.info.getComponent(), flags, reason, admin.getUserHandle().getIdentifier());
5205    }
5206
5207    private void wipeDataNoLock(ComponentName admin, int flags, String reason, int userId) {
5208        wtfIfInLock();
5209
5210        long ident = mInjector.binderClearCallingIdentity();
5211        try {
5212            // First check whether the admin is allowed to wipe the device/user/profile.
5213            final String restriction;
5214            if (userId == UserHandle.USER_SYSTEM) {
5215                restriction = UserManager.DISALLOW_FACTORY_RESET;
5216            } else if (isManagedProfile(userId)) {
5217                restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
5218            } else {
5219                restriction = UserManager.DISALLOW_REMOVE_USER;
5220            }
5221            if (isAdminAffectedByRestriction(admin, restriction, userId)) {
5222                throw new SecurityException("Cannot wipe data. " + restriction
5223                        + " restriction is set for user " + userId);
5224            }
5225
5226            if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
5227                if (!isDeviceOwner(admin, userId)) {
5228                    throw new SecurityException(
5229                            "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
5230                }
5231                PersistentDataBlockManager manager = (PersistentDataBlockManager)
5232                        mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
5233                if (manager != null) {
5234                    manager.wipe();
5235                }
5236            }
5237
5238            // TODO If split user is enabled and the device owner is set in the primary user
5239            // (rather than system), we should probably trigger factory reset. Current code just
5240            // removes that user (but still clears FRP...)
5241            if (userId == UserHandle.USER_SYSTEM) {
5242                forceWipeDeviceNoLock(/*wipeExtRequested=*/ (flags & WIPE_EXTERNAL_STORAGE) != 0,
5243                        reason);
5244            } else {
5245                forceWipeUser(userId);
5246            }
5247        } finally {
5248            mInjector.binderRestoreCallingIdentity(ident);
5249        }
5250    }
5251
5252    private void sendWipeProfileNotification() {
5253        String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
5254        Notification notification = new Notification.Builder(mContext)
5255                .setSmallIcon(android.R.drawable.stat_sys_warning)
5256                .setContentTitle(mContext.getString(R.string.work_profile_deleted))
5257                .setContentText(contentText)
5258                .setColor(mContext.getColor(R.color.system_notification_accent_color))
5259                .setStyle(new Notification.BigTextStyle().bigText(contentText))
5260                .build();
5261        mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
5262    }
5263
5264    private void clearWipeProfileNotification() {
5265        mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
5266    }
5267
5268    @Override
5269    public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
5270        if (!mHasFeature) {
5271            return;
5272        }
5273        enforceFullCrossUsersPermission(userHandle);
5274        mContext.enforceCallingOrSelfPermission(
5275                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5276
5277        synchronized (this) {
5278            ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
5279            if (admin == null) {
5280                result.sendResult(null);
5281                return;
5282            }
5283            Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
5284            intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
5285            intent.setComponent(admin.info.getComponent());
5286            mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
5287                    null, new BroadcastReceiver() {
5288                @Override
5289                public void onReceive(Context context, Intent intent) {
5290                    result.sendResult(getResultExtras(false));
5291                }
5292            }, null, Activity.RESULT_OK, null, null);
5293        }
5294    }
5295
5296    @Override
5297    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
5298        if (!mHasFeature) {
5299            return;
5300        }
5301        enforceFullCrossUsersPermission(userHandle);
5302        mContext.enforceCallingOrSelfPermission(
5303                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5304
5305        // If the managed profile doesn't have a separate password, set the metrics to default
5306        if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
5307            metrics = new PasswordMetrics();
5308        }
5309
5310        validateQualityConstant(metrics.quality);
5311        DevicePolicyData policy = getUserData(userHandle);
5312        synchronized (this) {
5313            policy.mActivePasswordMetrics = metrics;
5314        }
5315    }
5316
5317    @Override
5318    public void reportPasswordChanged(@UserIdInt int userId) {
5319        if (!mHasFeature) {
5320            return;
5321        }
5322        enforceFullCrossUsersPermission(userId);
5323
5324        // Managed Profile password can only be changed when it has a separate challenge.
5325        if (!isSeparateProfileChallengeEnabled(userId)) {
5326            enforceNotManagedProfile(userId, "set the active password");
5327        }
5328
5329        mContext.enforceCallingOrSelfPermission(
5330                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5331
5332        DevicePolicyData policy = getUserData(userId);
5333
5334        long ident = mInjector.binderClearCallingIdentity();
5335        try {
5336            synchronized (this) {
5337                policy.mFailedPasswordAttempts = 0;
5338                saveSettingsLocked(userId);
5339                updatePasswordExpirationsLocked(userId);
5340                setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
5341
5342                // Send a broadcast to each profile using this password as its primary unlock.
5343                sendAdminCommandForLockscreenPoliciesLocked(
5344                        DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
5345                        DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
5346            }
5347            removeCaApprovalsIfNeeded(userId);
5348        } finally {
5349            mInjector.binderRestoreCallingIdentity(ident);
5350        }
5351    }
5352
5353    /**
5354     * Called any time the device password is updated. Resets all password expiration clocks.
5355     */
5356    private void updatePasswordExpirationsLocked(int userHandle) {
5357        ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
5358        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5359                userHandle, /* parent */ false);
5360        final int N = admins.size();
5361        for (int i = 0; i < N; i++) {
5362            ActiveAdmin admin = admins.get(i);
5363            if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
5364                affectedUserIds.add(admin.getUserHandle().getIdentifier());
5365                long timeout = admin.passwordExpirationTimeout;
5366                long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
5367                admin.passwordExpirationDate = expiration;
5368            }
5369        }
5370        for (int affectedUserId : affectedUserIds) {
5371            saveSettingsLocked(affectedUserId);
5372        }
5373    }
5374
5375    @Override
5376    public void reportFailedPasswordAttempt(int userHandle) {
5377        enforceFullCrossUsersPermission(userHandle);
5378        if (!isSeparateProfileChallengeEnabled(userHandle)) {
5379            enforceNotManagedProfile(userHandle,
5380                    "report failed password attempt if separate profile challenge is not in place");
5381        }
5382        mContext.enforceCallingOrSelfPermission(
5383                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5384
5385        boolean wipeData = false;
5386        ActiveAdmin strictestAdmin = null;
5387        final long ident = mInjector.binderClearCallingIdentity();
5388        try {
5389            synchronized (this) {
5390                DevicePolicyData policy = getUserData(userHandle);
5391                policy.mFailedPasswordAttempts++;
5392                saveSettingsLocked(userHandle);
5393                if (mHasFeature) {
5394                    strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
5395                            userHandle, /* parent */ false);
5396                    int max = strictestAdmin != null
5397                            ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
5398                    if (max > 0 && policy.mFailedPasswordAttempts >= max) {
5399                        wipeData = true;
5400                    }
5401
5402                    sendAdminCommandForLockscreenPoliciesLocked(
5403                            DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
5404                            DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5405                }
5406            }
5407        } finally {
5408            mInjector.binderRestoreCallingIdentity(ident);
5409        }
5410
5411        if (wipeData && strictestAdmin != null) {
5412            final int userId = strictestAdmin.getUserHandle().getIdentifier();
5413            Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
5414                    + strictestAdmin.info.getComponent().flattenToShortString()
5415                    + ". Calling wipeData for user " + userId);
5416
5417            // Attempt to wipe the device/user/profile associated with the admin, as if the
5418            // admin had called wipeData(). That way we can check whether the admin is actually
5419            // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
5420            // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
5421            // able to do so).
5422            // IMPORTANT: Call without holding the lock to prevent deadlock.
5423            try {
5424                wipeDataNoLock(strictestAdmin.info.getComponent(),
5425                        /*flags=*/ 0,
5426                        /*reason=*/ "reportFailedPasswordAttempt()",
5427                        userId);
5428            } catch (SecurityException e) {
5429                Slog.w(LOG_TAG, "Failed to wipe user " + userId
5430                        + " after max failed password attempts reached.", e);
5431            }
5432        }
5433
5434        if (mInjector.securityLogIsLoggingEnabled()) {
5435            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5436                    /*method strength*/ 1);
5437        }
5438    }
5439
5440    @Override
5441    public void reportSuccessfulPasswordAttempt(int userHandle) {
5442        enforceFullCrossUsersPermission(userHandle);
5443        mContext.enforceCallingOrSelfPermission(
5444                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5445
5446        synchronized (this) {
5447            DevicePolicyData policy = getUserData(userHandle);
5448            if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
5449                long ident = mInjector.binderClearCallingIdentity();
5450                try {
5451                    policy.mFailedPasswordAttempts = 0;
5452                    policy.mPasswordOwner = -1;
5453                    saveSettingsLocked(userHandle);
5454                    if (mHasFeature) {
5455                        sendAdminCommandForLockscreenPoliciesLocked(
5456                                DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
5457                                DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5458                    }
5459                } finally {
5460                    mInjector.binderRestoreCallingIdentity(ident);
5461                }
5462            }
5463        }
5464
5465        if (mInjector.securityLogIsLoggingEnabled()) {
5466            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5467                    /*method strength*/ 1);
5468        }
5469    }
5470
5471    @Override
5472    public void reportFailedFingerprintAttempt(int userHandle) {
5473        enforceFullCrossUsersPermission(userHandle);
5474        mContext.enforceCallingOrSelfPermission(
5475                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5476        if (mInjector.securityLogIsLoggingEnabled()) {
5477            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5478                    /*method strength*/ 0);
5479        }
5480    }
5481
5482    @Override
5483    public void reportSuccessfulFingerprintAttempt(int userHandle) {
5484        enforceFullCrossUsersPermission(userHandle);
5485        mContext.enforceCallingOrSelfPermission(
5486                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5487        if (mInjector.securityLogIsLoggingEnabled()) {
5488            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5489                    /*method strength*/ 0);
5490        }
5491    }
5492
5493    @Override
5494    public void reportKeyguardDismissed(int userHandle) {
5495        enforceFullCrossUsersPermission(userHandle);
5496        mContext.enforceCallingOrSelfPermission(
5497                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5498
5499        if (mInjector.securityLogIsLoggingEnabled()) {
5500            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
5501        }
5502    }
5503
5504    @Override
5505    public void reportKeyguardSecured(int userHandle) {
5506        enforceFullCrossUsersPermission(userHandle);
5507        mContext.enforceCallingOrSelfPermission(
5508                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5509
5510        if (mInjector.securityLogIsLoggingEnabled()) {
5511            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
5512        }
5513    }
5514
5515    @Override
5516    public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
5517            String exclusionList) {
5518        if (!mHasFeature) {
5519            return null;
5520        }
5521        synchronized(this) {
5522            Preconditions.checkNotNull(who, "ComponentName is null");
5523
5524            // Only check if system user has set global proxy. We don't allow other users to set it.
5525            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5526            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5527                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
5528
5529            // Scan through active admins and find if anyone has already
5530            // set the global proxy.
5531            Set<ComponentName> compSet = policy.mAdminMap.keySet();
5532            for (ComponentName component : compSet) {
5533                ActiveAdmin ap = policy.mAdminMap.get(component);
5534                if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
5535                    // Another admin already sets the global proxy
5536                    // Return it to the caller.
5537                    return component;
5538                }
5539            }
5540
5541            // If the user is not system, don't set the global proxy. Fail silently.
5542            if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
5543                Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
5544                        + UserHandle.getCallingUserId() + " is not permitted.");
5545                return null;
5546            }
5547            if (proxySpec == null) {
5548                admin.specifiesGlobalProxy = false;
5549                admin.globalProxySpec = null;
5550                admin.globalProxyExclusionList = null;
5551            } else {
5552
5553                admin.specifiesGlobalProxy = true;
5554                admin.globalProxySpec = proxySpec;
5555                admin.globalProxyExclusionList = exclusionList;
5556            }
5557
5558            // Reset the global proxy accordingly
5559            // Do this using system permissions, as apps cannot write to secure settings
5560            long origId = mInjector.binderClearCallingIdentity();
5561            try {
5562                resetGlobalProxyLocked(policy);
5563            } finally {
5564                mInjector.binderRestoreCallingIdentity(origId);
5565            }
5566            return null;
5567        }
5568    }
5569
5570    @Override
5571    public ComponentName getGlobalProxyAdmin(int userHandle) {
5572        if (!mHasFeature) {
5573            return null;
5574        }
5575        enforceFullCrossUsersPermission(userHandle);
5576        synchronized(this) {
5577            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5578            // Scan through active admins and find if anyone has already
5579            // set the global proxy.
5580            final int N = policy.mAdminList.size();
5581            for (int i = 0; i < N; i++) {
5582                ActiveAdmin ap = policy.mAdminList.get(i);
5583                if (ap.specifiesGlobalProxy) {
5584                    // Device admin sets the global proxy
5585                    // Return it to the caller.
5586                    return ap.info.getComponent();
5587                }
5588            }
5589        }
5590        // No device admin sets the global proxy.
5591        return null;
5592    }
5593
5594    @Override
5595    public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5596        synchronized (this) {
5597            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5598        }
5599        long token = mInjector.binderClearCallingIdentity();
5600        try {
5601            ConnectivityManager connectivityManager = (ConnectivityManager)
5602                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5603            connectivityManager.setGlobalProxy(proxyInfo);
5604        } finally {
5605            mInjector.binderRestoreCallingIdentity(token);
5606        }
5607    }
5608
5609    private void resetGlobalProxyLocked(DevicePolicyData policy) {
5610        final int N = policy.mAdminList.size();
5611        for (int i = 0; i < N; i++) {
5612            ActiveAdmin ap = policy.mAdminList.get(i);
5613            if (ap.specifiesGlobalProxy) {
5614                saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5615                return;
5616            }
5617        }
5618        // No device admins defining global proxies - reset global proxy settings to none
5619        saveGlobalProxyLocked(null, null);
5620    }
5621
5622    private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5623        if (exclusionList == null) {
5624            exclusionList = "";
5625        }
5626        if (proxySpec == null) {
5627            proxySpec = "";
5628        }
5629        // Remove white spaces
5630        proxySpec = proxySpec.trim();
5631        String data[] = proxySpec.split(":");
5632        int proxyPort = 8080;
5633        if (data.length > 1) {
5634            try {
5635                proxyPort = Integer.parseInt(data[1]);
5636            } catch (NumberFormatException e) {}
5637        }
5638        exclusionList = exclusionList.trim();
5639
5640        ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5641        if (!proxyProperties.isValid()) {
5642            Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5643            return;
5644        }
5645        mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5646        mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5647        mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5648                exclusionList);
5649    }
5650
5651    /**
5652     * Set the storage encryption request for a single admin.  Returns the new total request
5653     * status (for all admins).
5654     */
5655    @Override
5656    public int setStorageEncryption(ComponentName who, boolean encrypt) {
5657        if (!mHasFeature) {
5658            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5659        }
5660        Preconditions.checkNotNull(who, "ComponentName is null");
5661        final int userHandle = UserHandle.getCallingUserId();
5662        synchronized (this) {
5663            // Check for permissions
5664            // Only system user can set storage encryption
5665            if (userHandle != UserHandle.USER_SYSTEM) {
5666                Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5667                        + UserHandle.getCallingUserId() + " is not permitted.");
5668                return 0;
5669            }
5670
5671            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5672                    DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5673
5674            // Quick exit:  If the filesystem does not support encryption, we can exit early.
5675            if (!isEncryptionSupported()) {
5676                return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5677            }
5678
5679            // (1) Record the value for the admin so it's sticky
5680            if (ap.encryptionRequested != encrypt) {
5681                ap.encryptionRequested = encrypt;
5682                saveSettingsLocked(userHandle);
5683            }
5684
5685            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5686            // (2) Compute "max" for all admins
5687            boolean newRequested = false;
5688            final int N = policy.mAdminList.size();
5689            for (int i = 0; i < N; i++) {
5690                newRequested |= policy.mAdminList.get(i).encryptionRequested;
5691            }
5692
5693            // Notify OS of new request
5694            setEncryptionRequested(newRequested);
5695
5696            // Return the new global request status
5697            return newRequested
5698                    ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5699                    : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5700        }
5701    }
5702
5703    /**
5704     * Get the current storage encryption request status for a given admin, or aggregate of all
5705     * active admins.
5706     */
5707    @Override
5708    public boolean getStorageEncryption(ComponentName who, int userHandle) {
5709        if (!mHasFeature) {
5710            return false;
5711        }
5712        enforceFullCrossUsersPermission(userHandle);
5713        synchronized (this) {
5714            // Check for permissions if a particular caller is specified
5715            if (who != null) {
5716                // When checking for a single caller, status is based on caller's request
5717                ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5718                return ap != null ? ap.encryptionRequested : false;
5719            }
5720
5721            // If no particular caller is specified, return the aggregate set of requests.
5722            // This is short circuited by returning true on the first hit.
5723            DevicePolicyData policy = getUserData(userHandle);
5724            final int N = policy.mAdminList.size();
5725            for (int i = 0; i < N; i++) {
5726                if (policy.mAdminList.get(i).encryptionRequested) {
5727                    return true;
5728                }
5729            }
5730            return false;
5731        }
5732    }
5733
5734    /**
5735     * Get the current encryption status of the device.
5736     */
5737    @Override
5738    public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5739        if (!mHasFeature) {
5740            // Ok to return current status.
5741        }
5742        enforceFullCrossUsersPermission(userHandle);
5743
5744        // It's not critical here, but let's make sure the package name is correct, in case
5745        // we start using it for different purposes.
5746        ensureCallerPackage(callerPackage);
5747
5748        final ApplicationInfo ai;
5749        try {
5750            ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5751        } catch (RemoteException e) {
5752            throw new SecurityException(e);
5753        }
5754
5755        boolean legacyApp = false;
5756        if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5757            legacyApp = true;
5758        }
5759
5760        final int rawStatus = getEncryptionStatus();
5761        if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5762            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5763        }
5764        return rawStatus;
5765    }
5766
5767    /**
5768     * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
5769     */
5770    private boolean isEncryptionSupported() {
5771        // Note, this can be implemented as
5772        //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5773        // But is provided as a separate internal method if there's a faster way to do a
5774        // simple check for supported-or-not.
5775        return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5776    }
5777
5778    /**
5779     * Hook to low-levels:  Reporting the current status of encryption.
5780     * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5781     * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5782     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5783     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5784     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5785     */
5786    private int getEncryptionStatus() {
5787        if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5788            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5789        } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5790            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5791        } else if (mInjector.storageManagerIsEncrypted()) {
5792            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5793        } else if (mInjector.storageManagerIsEncryptable()) {
5794            return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5795        } else {
5796            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5797        }
5798    }
5799
5800    /**
5801     * Hook to low-levels:  If needed, record the new admin setting for encryption.
5802     */
5803    private void setEncryptionRequested(boolean encrypt) {
5804    }
5805
5806    /**
5807     * Set whether the screen capture is disabled for the user managed by the specified admin.
5808     */
5809    @Override
5810    public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5811        if (!mHasFeature) {
5812            return;
5813        }
5814        Preconditions.checkNotNull(who, "ComponentName is null");
5815        final int userHandle = UserHandle.getCallingUserId();
5816        synchronized (this) {
5817            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5818                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5819            if (ap.disableScreenCapture != disabled) {
5820                ap.disableScreenCapture = disabled;
5821                saveSettingsLocked(userHandle);
5822                updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5823            }
5824        }
5825    }
5826
5827    /**
5828     * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5829     * active admin (if given admin is null).
5830     */
5831    @Override
5832    public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5833        if (!mHasFeature) {
5834            return false;
5835        }
5836        synchronized (this) {
5837            if (who != null) {
5838                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5839                return (admin != null) ? admin.disableScreenCapture : false;
5840            }
5841
5842            DevicePolicyData policy = getUserData(userHandle);
5843            final int N = policy.mAdminList.size();
5844            for (int i = 0; i < N; i++) {
5845                ActiveAdmin admin = policy.mAdminList.get(i);
5846                if (admin.disableScreenCapture) {
5847                    return true;
5848                }
5849            }
5850            return false;
5851        }
5852    }
5853
5854    private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5855            final boolean disabled) {
5856        mHandler.post(new Runnable() {
5857            @Override
5858            public void run() {
5859                try {
5860                    mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5861                } catch (RemoteException e) {
5862                    Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5863                }
5864            }
5865        });
5866    }
5867
5868    /**
5869     * Set whether auto time is required by the specified admin (must be device or profile owner).
5870     */
5871    @Override
5872    public void setAutoTimeRequired(ComponentName who, boolean required) {
5873        if (!mHasFeature) {
5874            return;
5875        }
5876        Preconditions.checkNotNull(who, "ComponentName is null");
5877        final int userHandle = UserHandle.getCallingUserId();
5878        synchronized (this) {
5879            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5880                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5881            if (admin.requireAutoTime != required) {
5882                admin.requireAutoTime = required;
5883                saveSettingsLocked(userHandle);
5884            }
5885        }
5886
5887        // Turn AUTO_TIME on in settings if it is required
5888        if (required) {
5889            long ident = mInjector.binderClearCallingIdentity();
5890            try {
5891                mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5892            } finally {
5893                mInjector.binderRestoreCallingIdentity(ident);
5894            }
5895        }
5896    }
5897
5898    /**
5899     * Returns whether or not auto time is required by the device owner or any profile owner.
5900     */
5901    @Override
5902    public boolean getAutoTimeRequired() {
5903        if (!mHasFeature) {
5904            return false;
5905        }
5906        synchronized (this) {
5907            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5908            if (deviceOwner != null && deviceOwner.requireAutoTime) {
5909                // If the device owner enforces auto time, we don't need to check the PO's
5910                return true;
5911            }
5912
5913            // Now check to see if any profile owner on any user enforces auto time
5914            for (Integer userId : mOwners.getProfileOwnerKeys()) {
5915                ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
5916                if (profileOwner != null && profileOwner.requireAutoTime) {
5917                    return true;
5918                }
5919            }
5920
5921            return false;
5922        }
5923    }
5924
5925    @Override
5926    public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5927        if (!mHasFeature) {
5928            return;
5929        }
5930        Preconditions.checkNotNull(who, "ComponentName is null");
5931        // Allow setting this policy to true only if there is a split system user.
5932        if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5933            throw new UnsupportedOperationException(
5934                    "Cannot force ephemeral users on systems without split system user.");
5935        }
5936        boolean removeAllUsers = false;
5937        synchronized (this) {
5938            final ActiveAdmin deviceOwner =
5939                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5940            if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5941                deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5942                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5943                mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5944                removeAllUsers = forceEphemeralUsers;
5945            }
5946        }
5947        if (removeAllUsers) {
5948            long identitity = mInjector.binderClearCallingIdentity();
5949            try {
5950                mUserManagerInternal.removeAllUsers();
5951            } finally {
5952                mInjector.binderRestoreCallingIdentity(identitity);
5953            }
5954        }
5955    }
5956
5957    @Override
5958    public boolean getForceEphemeralUsers(ComponentName who) {
5959        if (!mHasFeature) {
5960            return false;
5961        }
5962        Preconditions.checkNotNull(who, "ComponentName is null");
5963        synchronized (this) {
5964            final ActiveAdmin deviceOwner =
5965                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5966            return deviceOwner.forceEphemeralUsers;
5967        }
5968    }
5969
5970    private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) throws SecurityException {
5971        synchronized (this) {
5972            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5973            if (!areAllUsersAffiliatedWithDeviceLocked()) {
5974                throw new SecurityException("Not all users are affiliated.");
5975            }
5976        }
5977    }
5978
5979    @Override
5980    public boolean requestBugreport(ComponentName who) {
5981        if (!mHasFeature) {
5982            return false;
5983        }
5984        Preconditions.checkNotNull(who, "ComponentName is null");
5985
5986        // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
5987        // which could still contain data related to that user. Should we disallow that, e.g. until
5988        // next boot? Might not be needed given that this still requires user consent.
5989        ensureDeviceOwnerAndAllUsersAffiliated(who);
5990
5991        if (mRemoteBugreportServiceIsActive.get()
5992                || (getDeviceOwnerRemoteBugreportUri() != null)) {
5993            Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5994            return false;
5995        }
5996
5997        final long currentTime = System.currentTimeMillis();
5998        synchronized (this) {
5999            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
6000            if (currentTime > policyData.mLastBugReportRequestTime) {
6001                policyData.mLastBugReportRequestTime = currentTime;
6002                saveSettingsLocked(UserHandle.USER_SYSTEM);
6003            }
6004        }
6005
6006        final long callingIdentity = mInjector.binderClearCallingIdentity();
6007        try {
6008            mInjector.getIActivityManager().requestBugReport(
6009                    ActivityManager.BUGREPORT_OPTION_REMOTE);
6010
6011            mRemoteBugreportServiceIsActive.set(true);
6012            mRemoteBugreportSharingAccepted.set(false);
6013            registerRemoteBugreportReceivers();
6014            mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
6015                    RemoteBugreportUtils.NOTIFICATION_ID,
6016                    RemoteBugreportUtils.buildNotification(mContext,
6017                            DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
6018            mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
6019                    RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
6020            return true;
6021        } catch (RemoteException re) {
6022            // should never happen
6023            Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
6024            return false;
6025        } finally {
6026            mInjector.binderRestoreCallingIdentity(callingIdentity);
6027        }
6028    }
6029
6030    synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
6031        Intent intent = new Intent(action);
6032        intent.setComponent(mOwners.getDeviceOwnerComponent());
6033        if (extras != null) {
6034            intent.putExtras(extras);
6035        }
6036        mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
6037    }
6038
6039    private synchronized String getDeviceOwnerRemoteBugreportUri() {
6040        return mOwners.getDeviceOwnerRemoteBugreportUri();
6041    }
6042
6043    private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
6044            String bugreportHash) {
6045        mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
6046    }
6047
6048    private void registerRemoteBugreportReceivers() {
6049        try {
6050            IntentFilter filterFinished = new IntentFilter(
6051                    DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
6052                    RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6053            mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
6054        } catch (IntentFilter.MalformedMimeTypeException e) {
6055            // should never happen, as setting a constant
6056            Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
6057        }
6058        IntentFilter filterConsent = new IntentFilter();
6059        filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
6060        filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
6061        mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
6062    }
6063
6064    private void onBugreportFinished(Intent intent) {
6065        mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6066        mRemoteBugreportServiceIsActive.set(false);
6067        Uri bugreportUri = intent.getData();
6068        String bugreportUriString = null;
6069        if (bugreportUri != null) {
6070            bugreportUriString = bugreportUri.toString();
6071        }
6072        String bugreportHash = intent.getStringExtra(
6073                DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
6074        if (mRemoteBugreportSharingAccepted.get()) {
6075            shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6076            mInjector.getNotificationManager().cancel(LOG_TAG,
6077                    RemoteBugreportUtils.NOTIFICATION_ID);
6078        } else {
6079            setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
6080            mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6081                    RemoteBugreportUtils.buildNotification(mContext,
6082                            DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
6083                            UserHandle.ALL);
6084        }
6085        mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6086    }
6087
6088    private void onBugreportFailed() {
6089        mRemoteBugreportServiceIsActive.set(false);
6090        mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6091                RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6092        mRemoteBugreportSharingAccepted.set(false);
6093        setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6094        mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
6095        Bundle extras = new Bundle();
6096        extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6097                DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
6098        sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6099        mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
6100        mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6101    }
6102
6103    private void onBugreportSharingAccepted() {
6104        mRemoteBugreportSharingAccepted.set(true);
6105        String bugreportUriString = null;
6106        String bugreportHash = null;
6107        synchronized (this) {
6108            bugreportUriString = getDeviceOwnerRemoteBugreportUri();
6109            bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
6110        }
6111        if (bugreportUriString != null) {
6112            shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6113        } else if (mRemoteBugreportServiceIsActive.get()) {
6114            mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6115                    RemoteBugreportUtils.buildNotification(mContext,
6116                            DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
6117                            UserHandle.ALL);
6118        }
6119    }
6120
6121    private void onBugreportSharingDeclined() {
6122        if (mRemoteBugreportServiceIsActive.get()) {
6123            mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6124                    RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6125            mRemoteBugreportServiceIsActive.set(false);
6126            mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6127            mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6128        }
6129        mRemoteBugreportSharingAccepted.set(false);
6130        setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6131        sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
6132    }
6133
6134    private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
6135            String bugreportHash) {
6136        ParcelFileDescriptor pfd = null;
6137        try {
6138            if (bugreportUriString == null) {
6139                throw new FileNotFoundException();
6140            }
6141            Uri bugreportUri = Uri.parse(bugreportUriString);
6142            pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
6143
6144            synchronized (this) {
6145                Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
6146                intent.setComponent(mOwners.getDeviceOwnerComponent());
6147                intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6148                intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
6149                mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
6150                        bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6151                mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
6152            }
6153        } catch (FileNotFoundException e) {
6154            Bundle extras = new Bundle();
6155            extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6156                    DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
6157            sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6158        } finally {
6159            try {
6160                if (pfd != null) {
6161                    pfd.close();
6162                }
6163            } catch (IOException ex) {
6164                // Ignore
6165            }
6166            mRemoteBugreportSharingAccepted.set(false);
6167            setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6168        }
6169    }
6170
6171    /**
6172     * Disables all device cameras according to the specified admin.
6173     */
6174    @Override
6175    public void setCameraDisabled(ComponentName who, boolean disabled) {
6176        if (!mHasFeature) {
6177            return;
6178        }
6179        Preconditions.checkNotNull(who, "ComponentName is null");
6180        final int userHandle = mInjector.userHandleGetCallingUserId();
6181        synchronized (this) {
6182            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6183                    DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
6184            if (ap.disableCamera != disabled) {
6185                ap.disableCamera = disabled;
6186                saveSettingsLocked(userHandle);
6187            }
6188        }
6189        // Tell the user manager that the restrictions have changed.
6190        pushUserRestrictions(userHandle);
6191    }
6192
6193    /**
6194     * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
6195     * active admins.
6196     */
6197    @Override
6198    public boolean getCameraDisabled(ComponentName who, int userHandle) {
6199        return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
6200    }
6201
6202    private boolean getCameraDisabled(ComponentName who, int userHandle,
6203            boolean mergeDeviceOwnerRestriction) {
6204        if (!mHasFeature) {
6205            return false;
6206        }
6207        synchronized (this) {
6208            if (who != null) {
6209                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6210                return (admin != null) ? admin.disableCamera : false;
6211            }
6212            // First, see if DO has set it.  If so, it's device-wide.
6213            if (mergeDeviceOwnerRestriction) {
6214                final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6215                if (deviceOwner != null && deviceOwner.disableCamera) {
6216                    return true;
6217                }
6218            }
6219
6220            // Then check each device admin on the user.
6221            DevicePolicyData policy = getUserData(userHandle);
6222            // Determine whether or not the device camera is disabled for any active admins.
6223            final int N = policy.mAdminList.size();
6224            for (int i = 0; i < N; i++) {
6225                ActiveAdmin admin = policy.mAdminList.get(i);
6226                if (admin.disableCamera) {
6227                    return true;
6228                }
6229            }
6230            return false;
6231        }
6232    }
6233
6234    @Override
6235    public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
6236        if (!mHasFeature) {
6237            return;
6238        }
6239        Preconditions.checkNotNull(who, "ComponentName is null");
6240        final int userHandle = mInjector.userHandleGetCallingUserId();
6241        if (isManagedProfile(userHandle)) {
6242            if (parent) {
6243                which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
6244            } else {
6245                which = which & PROFILE_KEYGUARD_FEATURES;
6246            }
6247        }
6248        synchronized (this) {
6249            ActiveAdmin ap = getActiveAdminForCallerLocked(
6250                    who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6251            if (ap.disabledKeyguardFeatures != which) {
6252                ap.disabledKeyguardFeatures = which;
6253                saveSettingsLocked(userHandle);
6254            }
6255        }
6256    }
6257
6258    /**
6259     * Gets the disabled state for features in keyguard for the given admin,
6260     * or the aggregate of all active admins if who is null.
6261     */
6262    @Override
6263    public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
6264        if (!mHasFeature) {
6265            return 0;
6266        }
6267        enforceFullCrossUsersPermission(userHandle);
6268        final long ident = mInjector.binderClearCallingIdentity();
6269        try {
6270            synchronized (this) {
6271                if (who != null) {
6272                    ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
6273                    return (admin != null) ? admin.disabledKeyguardFeatures : 0;
6274                }
6275
6276                final List<ActiveAdmin> admins;
6277                if (!parent && isManagedProfile(userHandle)) {
6278                    // If we are being asked about a managed profile, just return keyguard features
6279                    // disabled by admins in the profile.
6280                    admins = getUserDataUnchecked(userHandle).mAdminList;
6281                } else {
6282                    // Otherwise return those set by admins in the user and its profiles.
6283                    admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6284                }
6285
6286                int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
6287                final int N = admins.size();
6288                for (int i = 0; i < N; i++) {
6289                    ActiveAdmin admin = admins.get(i);
6290                    int userId = admin.getUserHandle().getIdentifier();
6291                    boolean isRequestedUser = !parent && (userId == userHandle);
6292                    if (isRequestedUser || !isManagedProfile(userId)) {
6293                        // If we are being asked explicitly about this user
6294                        // return all disabled features even if its a managed profile.
6295                        which |= admin.disabledKeyguardFeatures;
6296                    } else {
6297                        // Otherwise a managed profile is only allowed to disable
6298                        // some features on the parent user.
6299                        which |= (admin.disabledKeyguardFeatures
6300                                & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
6301                    }
6302                }
6303                return which;
6304            }
6305        } finally {
6306            mInjector.binderRestoreCallingIdentity(ident);
6307        }
6308    }
6309
6310    @Override
6311    public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
6312            List<String> packageList) {
6313        if (!mHasFeature) {
6314            return;
6315        }
6316        Preconditions.checkNotNull(packageList, "packageList is null");
6317        final int userHandle = UserHandle.getCallingUserId();
6318        synchronized (this) {
6319            // Ensure the caller is a DO or a keep uninstalled packages delegate.
6320            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6321                    DELEGATION_KEEP_UNINSTALLED_PACKAGES);
6322            // Get the device owner
6323            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6324            // Set list of packages to be kept even if uninstalled.
6325            deviceOwner.keepUninstalledPackages = packageList;
6326            // Save settings.
6327            saveSettingsLocked(userHandle);
6328            // Notify package manager.
6329            mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
6330        }
6331    }
6332
6333    @Override
6334    public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
6335        if (!mHasFeature) {
6336            return null;
6337        }
6338        // TODO In split system user mode, allow apps on user 0 to query the list
6339        synchronized (this) {
6340            // Ensure the caller is a DO or a keep uninstalled packages delegate.
6341            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6342                    DELEGATION_KEEP_UNINSTALLED_PACKAGES);
6343            return getKeepUninstalledPackagesLocked();
6344        }
6345    }
6346
6347    private List<String> getKeepUninstalledPackagesLocked() {
6348        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6349        return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
6350    }
6351
6352    @Override
6353    public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
6354        if (!mHasFeature) {
6355            return false;
6356        }
6357        if (admin == null
6358                || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
6359            throw new IllegalArgumentException("Invalid component " + admin
6360                    + " for device owner");
6361        }
6362        final boolean hasIncompatibleAccountsOrNonAdb =
6363                hasIncompatibleAccountsOrNonAdbNoLock(userId, admin);
6364        synchronized (this) {
6365            enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb);
6366            final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
6367            if (activeAdmin == null
6368                    || getUserData(userId).mRemovingAdmins.contains(admin)) {
6369                throw new IllegalArgumentException("Not active admin: " + admin);
6370            }
6371
6372            // Shutting down backup manager service permanently.
6373            long ident = mInjector.binderClearCallingIdentity();
6374            try {
6375                if (mInjector.getIBackupManager() != null) {
6376                    mInjector.getIBackupManager()
6377                            .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
6378                }
6379            } catch (RemoteException e) {
6380                throw new IllegalStateException("Failed deactivating backup service.", e);
6381            } finally {
6382                mInjector.binderRestoreCallingIdentity(ident);
6383            }
6384
6385            if (isAdb()) {
6386                // Log device owner provisioning was started using adb.
6387                MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
6388            }
6389
6390            mOwners.setDeviceOwner(admin, ownerName, userId);
6391            mOwners.writeDeviceOwner();
6392            updateDeviceOwnerLocked();
6393            setDeviceOwnerSystemPropertyLocked();
6394
6395            final Set<String> restrictions =
6396                    UserRestrictionsUtils.getDefaultEnabledForDeviceOwner();
6397            if (!restrictions.isEmpty()) {
6398                for (String restriction : restrictions) {
6399                    activeAdmin.ensureUserRestrictions().putBoolean(restriction, true);
6400                }
6401                activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions);
6402                Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions);
6403
6404                saveUserRestrictionsLocked(userId);
6405            }
6406
6407            ident = mInjector.binderClearCallingIdentity();
6408            try {
6409                // TODO Send to system too?
6410                mContext.sendBroadcastAsUser(
6411                        new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED)
6412                                .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND),
6413                        UserHandle.of(userId));
6414            } finally {
6415                mInjector.binderRestoreCallingIdentity(ident);
6416            }
6417            Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
6418            return true;
6419        }
6420    }
6421
6422    @Override
6423    public boolean hasDeviceOwner() {
6424        enforceDeviceOwnerOrManageUsers();
6425        return mOwners.hasDeviceOwner();
6426    }
6427
6428    boolean isDeviceOwner(ActiveAdmin admin) {
6429        return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
6430    }
6431
6432    public boolean isDeviceOwner(ComponentName who, int userId) {
6433        synchronized (this) {
6434            return mOwners.hasDeviceOwner()
6435                    && mOwners.getDeviceOwnerUserId() == userId
6436                    && mOwners.getDeviceOwnerComponent().equals(who);
6437        }
6438    }
6439
6440    private boolean isDeviceOwnerPackage(String packageName, int userId) {
6441        synchronized (this) {
6442            return mOwners.hasDeviceOwner()
6443                    && mOwners.getDeviceOwnerUserId() == userId
6444                    && mOwners.getDeviceOwnerPackageName().equals(packageName);
6445        }
6446    }
6447
6448    private boolean isProfileOwnerPackage(String packageName, int userId) {
6449        synchronized (this) {
6450            return mOwners.hasProfileOwner(userId)
6451                    && mOwners.getProfileOwnerPackage(userId).equals(packageName);
6452        }
6453    }
6454
6455    public boolean isProfileOwner(ComponentName who, int userId) {
6456        final ComponentName profileOwner = getProfileOwner(userId);
6457        return who != null && who.equals(profileOwner);
6458    }
6459
6460    @Override
6461    public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
6462        if (!mHasFeature) {
6463            return null;
6464        }
6465        if (!callingUserOnly) {
6466            enforceManageUsers();
6467        }
6468        synchronized (this) {
6469            if (!mOwners.hasDeviceOwner()) {
6470                return null;
6471            }
6472            if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
6473                    mOwners.getDeviceOwnerUserId()) {
6474                return null;
6475            }
6476            return mOwners.getDeviceOwnerComponent();
6477        }
6478    }
6479
6480    @Override
6481    public int getDeviceOwnerUserId() {
6482        if (!mHasFeature) {
6483            return UserHandle.USER_NULL;
6484        }
6485        enforceManageUsers();
6486        synchronized (this) {
6487            return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
6488        }
6489    }
6490
6491    /**
6492     * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
6493     * MANAGE_USERS.
6494     */
6495    @Override
6496    public String getDeviceOwnerName() {
6497        if (!mHasFeature) {
6498            return null;
6499        }
6500        enforceManageUsers();
6501        synchronized (this) {
6502            if (!mOwners.hasDeviceOwner()) {
6503                return null;
6504            }
6505            // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
6506            // Should setDeviceOwner/ProfileOwner still take a name?
6507            String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
6508            return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
6509        }
6510    }
6511
6512    /** Returns the active device owner or {@code null} if there is no device owner. */
6513    @VisibleForTesting
6514    ActiveAdmin getDeviceOwnerAdminLocked() {
6515        ComponentName component = mOwners.getDeviceOwnerComponent();
6516        if (component == null) {
6517            return null;
6518        }
6519
6520        DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
6521        final int n = policy.mAdminList.size();
6522        for (int i = 0; i < n; i++) {
6523            ActiveAdmin admin = policy.mAdminList.get(i);
6524            if (component.equals(admin.info.getComponent())) {
6525                return admin;
6526            }
6527        }
6528        Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
6529        return null;
6530    }
6531
6532    @Override
6533    public void clearDeviceOwner(String packageName) {
6534        Preconditions.checkNotNull(packageName, "packageName is null");
6535        final int callingUid = mInjector.binderGetCallingUid();
6536        try {
6537            int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName,
6538                    UserHandle.getUserId(callingUid));
6539            if (uid != callingUid) {
6540                throw new SecurityException("Invalid packageName");
6541            }
6542        } catch (NameNotFoundException e) {
6543            throw new SecurityException(e);
6544        }
6545        synchronized (this) {
6546            final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6547            final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6548            if (!mOwners.hasDeviceOwner()
6549                    || !deviceOwnerComponent.getPackageName().equals(packageName)
6550                    || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
6551                throw new SecurityException(
6552                        "clearDeviceOwner can only be called by the device owner");
6553            }
6554            enforceUserUnlocked(deviceOwnerUserId);
6555
6556            final ActiveAdmin admin = getDeviceOwnerAdminLocked();
6557            long ident = mInjector.binderClearCallingIdentity();
6558            try {
6559                clearDeviceOwnerLocked(admin, deviceOwnerUserId);
6560                removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
6561                Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
6562                intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
6563                mContext.sendBroadcastAsUser(intent, UserHandle.of(deviceOwnerUserId));
6564            } finally {
6565                mInjector.binderRestoreCallingIdentity(ident);
6566            }
6567            Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
6568        }
6569    }
6570
6571    private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
6572        if (admin != null) {
6573            admin.disableCamera = false;
6574            admin.userRestrictions = null;
6575            admin.defaultEnabledRestrictionsAlreadySet.clear();
6576            admin.forceEphemeralUsers = false;
6577            admin.isNetworkLoggingEnabled = false;
6578            mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
6579            final DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
6580            policyData.mLastSecurityLogRetrievalTime = -1;
6581            policyData.mLastBugReportRequestTime = -1;
6582            policyData.mLastNetworkLogsRetrievalTime = -1;
6583            saveSettingsLocked(UserHandle.USER_SYSTEM);
6584        }
6585        clearUserPoliciesLocked(userId);
6586
6587        mOwners.clearDeviceOwner();
6588        mOwners.writeDeviceOwner();
6589        updateDeviceOwnerLocked();
6590
6591        mInjector.securityLogSetLoggingEnabledProperty(false);
6592        mSecurityLogMonitor.stop();
6593        setNetworkLoggingActiveInternal(false);
6594
6595        try {
6596            if (mInjector.getIBackupManager() != null) {
6597                // Reactivate backup service.
6598                mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6599            }
6600        } catch (RemoteException e) {
6601            throw new IllegalStateException("Failed reactivating backup service.", e);
6602        }
6603    }
6604
6605    @Override
6606    public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6607        if (!mHasFeature) {
6608            return false;
6609        }
6610        if (who == null
6611                || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6612            throw new IllegalArgumentException("Component " + who
6613                    + " not installed for userId:" + userHandle);
6614        }
6615        final boolean hasIncompatibleAccountsOrNonAdb =
6616                hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who);
6617        synchronized (this) {
6618            enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb);
6619
6620            if (getActiveAdminUncheckedLocked(who, userHandle) == null
6621                    || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6622                throw new IllegalArgumentException("Not active admin: " + who);
6623            }
6624
6625            if (isAdb()) {
6626                // Log profile owner provisioning was started using adb.
6627                MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
6628            }
6629
6630            mOwners.setProfileOwner(who, ownerName, userHandle);
6631            mOwners.writeProfileOwner(userHandle);
6632            Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6633
6634            return true;
6635        }
6636    }
6637
6638    @Override
6639    public void clearProfileOwner(ComponentName who) {
6640        if (!mHasFeature) {
6641            return;
6642        }
6643        final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
6644        final int userId = callingUser.getIdentifier();
6645        enforceNotManagedProfile(userId, "clear profile owner");
6646        enforceUserUnlocked(userId);
6647        // Check if this is the profile owner who is calling
6648        final ActiveAdmin admin =
6649                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6650        synchronized (this) {
6651            final long ident = mInjector.binderClearCallingIdentity();
6652            try {
6653                clearProfileOwnerLocked(admin, userId);
6654                removeActiveAdminLocked(who, userId);
6655            } finally {
6656                mInjector.binderRestoreCallingIdentity(ident);
6657            }
6658            Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6659        }
6660    }
6661
6662    public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6663        if (admin != null) {
6664            admin.disableCamera = false;
6665            admin.userRestrictions = null;
6666            admin.defaultEnabledRestrictionsAlreadySet.clear();
6667        }
6668        clearUserPoliciesLocked(userId);
6669        mOwners.removeProfileOwner(userId);
6670        mOwners.writeProfileOwner(userId);
6671    }
6672
6673    @Override
6674    public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6675        Preconditions.checkNotNull(who, "ComponentName is null");
6676        if (!mHasFeature) {
6677            return;
6678        }
6679
6680        synchronized (this) {
6681            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6682            long token = mInjector.binderClearCallingIdentity();
6683            try {
6684                mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6685            } finally {
6686                mInjector.binderRestoreCallingIdentity(token);
6687            }
6688        }
6689    }
6690
6691    @Override
6692    public CharSequence getDeviceOwnerLockScreenInfo() {
6693        return mLockPatternUtils.getDeviceOwnerInfo();
6694    }
6695
6696    private void clearUserPoliciesLocked(int userId) {
6697        // Reset some of the user-specific policies.
6698        final DevicePolicyData policy = getUserData(userId);
6699        policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6700        // Clear delegations.
6701        policy.mDelegationMap.clear();
6702        policy.mStatusBarDisabled = false;
6703        policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6704        saveSettingsLocked(userId);
6705
6706        try {
6707            mIPackageManager.updatePermissionFlagsForAllApps(
6708                    PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6709                    0  /* flagValues */, userId);
6710            pushUserRestrictions(userId);
6711        } catch (RemoteException re) {
6712            // Shouldn't happen.
6713        }
6714    }
6715
6716    @Override
6717    public boolean hasUserSetupCompleted() {
6718        return hasUserSetupCompleted(UserHandle.getCallingUserId());
6719    }
6720
6721    // This checks only if the Setup Wizard has run.  Since Wear devices pair before
6722    // completing Setup Wizard, and pairing involves transferring user data, calling
6723    // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
6724    private boolean hasUserSetupCompleted(int userHandle) {
6725        if (!mHasFeature) {
6726            return true;
6727        }
6728        return getUserData(userHandle).mUserSetupComplete;
6729    }
6730
6731    private boolean hasPaired(int userHandle) {
6732        if (!mHasFeature) {
6733            return true;
6734        }
6735        return getUserData(userHandle).mPaired;
6736    }
6737
6738    @Override
6739    public int getUserProvisioningState() {
6740        if (!mHasFeature) {
6741            return DevicePolicyManager.STATE_USER_UNMANAGED;
6742        }
6743        int userHandle = mInjector.userHandleGetCallingUserId();
6744        return getUserProvisioningState(userHandle);
6745    }
6746
6747    private int getUserProvisioningState(int userHandle) {
6748        return getUserData(userHandle).mUserProvisioningState;
6749    }
6750
6751    @Override
6752    public void setUserProvisioningState(int newState, int userHandle) {
6753        if (!mHasFeature) {
6754            return;
6755        }
6756
6757        if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6758                && getManagedUserId(userHandle) == -1) {
6759            // No managed device, user or profile, so setting provisioning state makes no sense.
6760            throw new IllegalStateException("Not allowed to change provisioning state unless a "
6761                      + "device or profile owner is set.");
6762        }
6763
6764        synchronized (this) {
6765            boolean transitionCheckNeeded = true;
6766
6767            // Calling identity/permission checks.
6768            if (isAdb()) {
6769                // ADB shell can only move directly from un-managed to finalized as part of directly
6770                // setting profile-owner or device-owner.
6771                if (getUserProvisioningState(userHandle) !=
6772                        DevicePolicyManager.STATE_USER_UNMANAGED
6773                        || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6774                    throw new IllegalStateException("Not allowed to change provisioning state "
6775                            + "unless current provisioning state is unmanaged, and new state is "
6776                            + "finalized.");
6777                }
6778                transitionCheckNeeded = false;
6779            } else {
6780                // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6781                enforceCanManageProfileAndDeviceOwners();
6782            }
6783
6784            final DevicePolicyData policyData = getUserData(userHandle);
6785            if (transitionCheckNeeded) {
6786                // Optional state transition check for non-ADB case.
6787                checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6788            }
6789            policyData.mUserProvisioningState = newState;
6790            saveSettingsLocked(userHandle);
6791        }
6792    }
6793
6794    private void checkUserProvisioningStateTransition(int currentState, int newState) {
6795        // Valid transitions for normal use-cases.
6796        switch (currentState) {
6797            case DevicePolicyManager.STATE_USER_UNMANAGED:
6798                // Can move to any state from unmanaged (except itself as an edge case)..
6799                if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6800                    return;
6801                }
6802                break;
6803            case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6804            case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6805                // Can only move to finalized from these states.
6806                if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6807                    return;
6808                }
6809                break;
6810            case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6811                // Current user has a managed-profile, but current user is not managed, so
6812                // rather than moving to finalized state, go back to unmanaged once
6813                // profile provisioning is complete.
6814                if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6815                    return;
6816                }
6817                break;
6818            case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6819                // Cannot transition out of finalized.
6820                break;
6821        }
6822
6823        // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6824        throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6825                + "from state [" + currentState + "]");
6826    }
6827
6828    @Override
6829    public void setProfileEnabled(ComponentName who) {
6830        if (!mHasFeature) {
6831            return;
6832        }
6833        Preconditions.checkNotNull(who, "ComponentName is null");
6834        synchronized (this) {
6835            // Check if this is the profile owner who is calling
6836            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6837            final int userId = UserHandle.getCallingUserId();
6838            enforceManagedProfile(userId, "enable the profile");
6839            // Check if the profile is already enabled.
6840            UserInfo managedProfile = getUserInfo(userId);
6841            if (managedProfile.isEnabled()) {
6842                Slog.e(LOG_TAG,
6843                        "setProfileEnabled is called when the profile is already enabled");
6844                return;
6845            }
6846            long id = mInjector.binderClearCallingIdentity();
6847            try {
6848                mUserManager.setUserEnabled(userId);
6849                UserInfo parent = mUserManager.getProfileParent(userId);
6850                Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6851                intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6852                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6853                        Intent.FLAG_RECEIVER_FOREGROUND);
6854                mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6855            } finally {
6856                mInjector.binderRestoreCallingIdentity(id);
6857            }
6858        }
6859    }
6860
6861    @Override
6862    public void setProfileName(ComponentName who, String profileName) {
6863        Preconditions.checkNotNull(who, "ComponentName is null");
6864        int userId = UserHandle.getCallingUserId();
6865        // Check if this is the profile owner (includes device owner).
6866        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6867
6868        long id = mInjector.binderClearCallingIdentity();
6869        try {
6870            mUserManager.setUserName(userId, profileName);
6871        } finally {
6872            mInjector.binderRestoreCallingIdentity(id);
6873        }
6874    }
6875
6876    @Override
6877    public ComponentName getProfileOwner(int userHandle) {
6878        if (!mHasFeature) {
6879            return null;
6880        }
6881
6882        synchronized (this) {
6883            return mOwners.getProfileOwnerComponent(userHandle);
6884        }
6885    }
6886
6887    // Returns the active profile owner for this user or null if the current user has no
6888    // profile owner.
6889    @VisibleForTesting
6890    ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6891        ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6892        if (profileOwner == null) {
6893            return null;
6894        }
6895        DevicePolicyData policy = getUserData(userHandle);
6896        final int n = policy.mAdminList.size();
6897        for (int i = 0; i < n; i++) {
6898            ActiveAdmin admin = policy.mAdminList.get(i);
6899            if (profileOwner.equals(admin.info.getComponent())) {
6900                return admin;
6901            }
6902        }
6903        return null;
6904    }
6905
6906    @Override
6907    public String getProfileOwnerName(int userHandle) {
6908        if (!mHasFeature) {
6909            return null;
6910        }
6911        enforceManageUsers();
6912        ComponentName profileOwner = getProfileOwner(userHandle);
6913        if (profileOwner == null) {
6914            return null;
6915        }
6916        return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6917    }
6918
6919    /**
6920     * Canonical name for a given package.
6921     */
6922    private String getApplicationLabel(String packageName, int userHandle) {
6923        long token = mInjector.binderClearCallingIdentity();
6924        try {
6925            final Context userContext;
6926            try {
6927                UserHandle handle = new UserHandle(userHandle);
6928                userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6929            } catch (PackageManager.NameNotFoundException nnfe) {
6930                Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6931                return null;
6932            }
6933            ApplicationInfo appInfo = userContext.getApplicationInfo();
6934            CharSequence result = null;
6935            if (appInfo != null) {
6936                PackageManager pm = userContext.getPackageManager();
6937                result = pm.getApplicationLabel(appInfo);
6938            }
6939            return result != null ? result.toString() : null;
6940        } finally {
6941            mInjector.binderRestoreCallingIdentity(token);
6942        }
6943    }
6944
6945    /**
6946     * Calls wtfStack() if called with the DPMS lock held.
6947     */
6948    private void wtfIfInLock() {
6949        if (Thread.holdsLock(this)) {
6950            Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
6951        }
6952    }
6953
6954    /**
6955     * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6956     * permission.
6957     * The profile owner can only be set before the user setup phase has completed,
6958     * except for:
6959     * - SYSTEM_UID
6960     * - adb unless hasIncompatibleAccountsOrNonAdb is true.
6961     */
6962    private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle,
6963            boolean hasIncompatibleAccountsOrNonAdb) {
6964        UserInfo info = getUserInfo(userHandle);
6965        if (info == null) {
6966            // User doesn't exist.
6967            throw new IllegalArgumentException(
6968                    "Attempted to set profile owner for invalid userId: " + userHandle);
6969        }
6970        if (info.isGuest()) {
6971            throw new IllegalStateException("Cannot set a profile owner on a guest");
6972        }
6973        if (mOwners.hasProfileOwner(userHandle)) {
6974            throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6975                    + "is already set.");
6976        }
6977        if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6978            throw new IllegalStateException("Trying to set the profile owner, but the user "
6979                    + "already has a device owner.");
6980        }
6981        if (isAdb()) {
6982            if ((mIsWatch || hasUserSetupCompleted(userHandle))
6983                    && hasIncompatibleAccountsOrNonAdb) {
6984                throw new IllegalStateException("Not allowed to set the profile owner because "
6985                        + "there are already some accounts on the profile");
6986            }
6987            return;
6988        }
6989        enforceCanManageProfileAndDeviceOwners();
6990        if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
6991            throw new IllegalStateException("Cannot set the profile owner on a user which is "
6992                    + "already set-up");
6993        }
6994    }
6995
6996    /**
6997     * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6998     * permission.
6999     */
7000    private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId,
7001            boolean hasIncompatibleAccountsOrNonAdb) {
7002        if (!isAdb()) {
7003            enforceCanManageProfileAndDeviceOwners();
7004        }
7005
7006        final int code = checkDeviceOwnerProvisioningPreConditionLocked(
7007                owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb);
7008        switch (code) {
7009            case CODE_OK:
7010                return;
7011            case CODE_HAS_DEVICE_OWNER:
7012                throw new IllegalStateException(
7013                        "Trying to set the device owner, but device owner is already set.");
7014            case CODE_USER_HAS_PROFILE_OWNER:
7015                throw new IllegalStateException("Trying to set the device owner, but the user "
7016                        + "already has a profile owner.");
7017            case CODE_USER_NOT_RUNNING:
7018                throw new IllegalStateException("User not running: " + userId);
7019            case CODE_NOT_SYSTEM_USER:
7020                throw new IllegalStateException("User is not system user");
7021            case CODE_USER_SETUP_COMPLETED:
7022                throw new IllegalStateException(
7023                        "Cannot set the device owner if the device is already set-up");
7024            case CODE_NONSYSTEM_USER_EXISTS:
7025                throw new IllegalStateException("Not allowed to set the device owner because there "
7026                        + "are already several users on the device");
7027            case CODE_ACCOUNTS_NOT_EMPTY:
7028                throw new IllegalStateException("Not allowed to set the device owner because there "
7029                        + "are already some accounts on the device");
7030            case CODE_HAS_PAIRED:
7031                throw new IllegalStateException("Not allowed to set the device owner because this "
7032                        + "device has already paired");
7033            default:
7034                throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code);
7035        }
7036    }
7037
7038    private void enforceUserUnlocked(int userId) {
7039        // Since we're doing this operation on behalf of an app, we only
7040        // want to use the actual "unlocked" state.
7041        Preconditions.checkState(mUserManager.isUserUnlocked(userId),
7042                "User must be running and unlocked");
7043    }
7044
7045    private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
7046        if (parent) {
7047            enforceUserUnlocked(getProfileParentId(userId));
7048        } else {
7049            enforceUserUnlocked(userId);
7050        }
7051    }
7052
7053    private void enforceManageUsers() {
7054        final int callingUid = mInjector.binderGetCallingUid();
7055        if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
7056            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7057        }
7058    }
7059
7060    private void enforceFullCrossUsersPermission(int userHandle) {
7061        enforceSystemUserOrPermission(userHandle,
7062                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
7063    }
7064
7065    private void enforceCrossUsersPermission(int userHandle) {
7066        enforceSystemUserOrPermission(userHandle,
7067                android.Manifest.permission.INTERACT_ACROSS_USERS);
7068    }
7069
7070    private void enforceSystemUserOrPermission(int userHandle, String permission) {
7071        if (userHandle < 0) {
7072            throw new IllegalArgumentException("Invalid userId " + userHandle);
7073        }
7074        final int callingUid = mInjector.binderGetCallingUid();
7075        if (userHandle == UserHandle.getUserId(callingUid)) {
7076            return;
7077        }
7078        if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
7079            mContext.enforceCallingOrSelfPermission(permission,
7080                    "Must be system or have " + permission + " permission");
7081        }
7082    }
7083
7084    private void enforceManagedProfile(int userHandle, String message) {
7085        if(!isManagedProfile(userHandle)) {
7086            throw new SecurityException("You can not " + message + " outside a managed profile.");
7087        }
7088    }
7089
7090    private void enforceNotManagedProfile(int userHandle, String message) {
7091        if(isManagedProfile(userHandle)) {
7092            throw new SecurityException("You can not " + message + " for a managed profile.");
7093        }
7094    }
7095
7096    private void enforceDeviceOwnerOrManageUsers() {
7097        synchronized (this) {
7098            if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7099                    mInjector.binderGetCallingUid()) != null) {
7100                return;
7101            }
7102        }
7103        enforceManageUsers();
7104    }
7105
7106    private void enforceProfileOwnerOrSystemUser(ComponentName admin) {
7107        synchronized (this) {
7108            if (getActiveAdminWithPolicyForUidLocked(admin,
7109                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7110                            != null) {
7111                return;
7112            }
7113        }
7114        Preconditions.checkState(isCallerWithSystemUid(),
7115                "Only profile owner, device owner and system may call this method.");
7116    }
7117
7118    private void ensureCallerPackage(@Nullable String packageName) {
7119        if (packageName == null) {
7120            Preconditions.checkState(isCallerWithSystemUid(),
7121                    "Only caller can omit package name");
7122        } else {
7123            final int callingUid = mInjector.binderGetCallingUid();
7124            final int userId = mInjector.userHandleGetCallingUserId();
7125            try {
7126                final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
7127                        packageName, 0, userId);
7128                Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
7129            } catch (RemoteException e) {
7130                // Shouldn't happen
7131            }
7132        }
7133    }
7134
7135    private boolean isCallerWithSystemUid() {
7136        return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
7137    }
7138
7139    private int getProfileParentId(int userHandle) {
7140        final long ident = mInjector.binderClearCallingIdentity();
7141        try {
7142            UserInfo parentUser = mUserManager.getProfileParent(userHandle);
7143            return parentUser != null ? parentUser.id : userHandle;
7144        } finally {
7145            mInjector.binderRestoreCallingIdentity(ident);
7146        }
7147    }
7148
7149    private int getCredentialOwner(int userHandle, boolean parent) {
7150        final long ident = mInjector.binderClearCallingIdentity();
7151        try {
7152            if (parent) {
7153                UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
7154                if (parentProfile != null) {
7155                    userHandle = parentProfile.id;
7156                }
7157            }
7158            return mUserManager.getCredentialOwnerProfile(userHandle);
7159        } finally {
7160            mInjector.binderRestoreCallingIdentity(ident);
7161        }
7162    }
7163
7164    private boolean isManagedProfile(int userHandle) {
7165        final UserInfo user = getUserInfo(userHandle);
7166        return user != null && user.isManagedProfile();
7167    }
7168
7169    private void enableIfNecessary(String packageName, int userId) {
7170        try {
7171            ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
7172                    PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
7173                    userId);
7174            if (ai.enabledSetting
7175                    == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
7176                mIPackageManager.setApplicationEnabledSetting(packageName,
7177                        PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
7178                        PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
7179            }
7180        } catch (RemoteException e) {
7181        }
7182    }
7183
7184    @Override
7185    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7186        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
7187                != PackageManager.PERMISSION_GRANTED) {
7188
7189            pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
7190                    + mInjector.binderGetCallingPid()
7191                    + ", uid=" + mInjector.binderGetCallingUid());
7192            return;
7193        }
7194
7195        synchronized (this) {
7196            pw.println("Current Device Policy Manager state:");
7197            mOwners.dump("  ", pw);
7198            int userCount = mUserData.size();
7199            for (int u = 0; u < userCount; u++) {
7200                DevicePolicyData policy = getUserData(mUserData.keyAt(u));
7201                pw.println();
7202                pw.println("  Enabled Device Admins (User " + policy.mUserHandle
7203                        + ", provisioningState: " + policy.mUserProvisioningState + "):");
7204                final int N = policy.mAdminList.size();
7205                for (int i=0; i<N; i++) {
7206                    ActiveAdmin ap = policy.mAdminList.get(i);
7207                    if (ap != null) {
7208                        pw.print("    "); pw.print(ap.info.getComponent().flattenToShortString());
7209                                pw.println(":");
7210                        ap.dump("      ", pw);
7211                    }
7212                }
7213                if (!policy.mRemovingAdmins.isEmpty()) {
7214                    pw.println("    Removing Device Admins (User " + policy.mUserHandle + "): "
7215                            + policy.mRemovingAdmins);
7216                }
7217
7218                pw.println(" ");
7219                pw.print("    mPasswordOwner="); pw.println(policy.mPasswordOwner);
7220            }
7221            pw.println();
7222            pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
7223        }
7224    }
7225
7226    private String getEncryptionStatusName(int encryptionStatus) {
7227        switch (encryptionStatus) {
7228            case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
7229                return "inactive";
7230            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
7231                return "block default key";
7232            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
7233                return "block";
7234            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
7235                return "per-user";
7236            case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
7237                return "unsupported";
7238            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
7239                return "activating";
7240            default:
7241                return "unknown";
7242        }
7243    }
7244
7245    @Override
7246    public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
7247            ComponentName activity) {
7248        Preconditions.checkNotNull(who, "ComponentName is null");
7249        final int userHandle = UserHandle.getCallingUserId();
7250        synchronized (this) {
7251            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7252
7253            long id = mInjector.binderClearCallingIdentity();
7254            try {
7255                mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
7256            } catch (RemoteException re) {
7257                // Shouldn't happen
7258            } finally {
7259                mInjector.binderRestoreCallingIdentity(id);
7260            }
7261        }
7262    }
7263
7264    @Override
7265    public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
7266        Preconditions.checkNotNull(who, "ComponentName is null");
7267        final int userHandle = UserHandle.getCallingUserId();
7268        synchronized (this) {
7269            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7270
7271            long id = mInjector.binderClearCallingIdentity();
7272            try {
7273                mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
7274            } catch (RemoteException re) {
7275                // Shouldn't happen
7276            } finally {
7277                mInjector.binderRestoreCallingIdentity(id);
7278            }
7279        }
7280    }
7281
7282    @Override
7283    public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
7284            String packageName) {
7285        try {
7286            setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
7287        } catch (IllegalArgumentException e) {
7288            return false;
7289        }
7290        return true;
7291    }
7292
7293    @Override
7294    public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
7295        final List<String> delegatePackages = getDelegatePackages(admin,
7296                DELEGATION_APP_RESTRICTIONS);
7297        return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
7298    }
7299
7300    @Override
7301    public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
7302        return isCallerDelegate(callerPackage, DELEGATION_APP_RESTRICTIONS);
7303    }
7304
7305    @Override
7306    public void setApplicationRestrictions(ComponentName who, String callerPackage,
7307            String packageName, Bundle settings) {
7308        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
7309                DELEGATION_APP_RESTRICTIONS);
7310
7311        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7312        final long id = mInjector.binderClearCallingIdentity();
7313        try {
7314            mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
7315        } finally {
7316            mInjector.binderRestoreCallingIdentity(id);
7317        }
7318    }
7319
7320    @Override
7321    public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
7322            PersistableBundle args, boolean parent) {
7323        if (!mHasFeature) {
7324            return;
7325        }
7326        Preconditions.checkNotNull(admin, "admin is null");
7327        Preconditions.checkNotNull(agent, "agent is null");
7328        final int userHandle = UserHandle.getCallingUserId();
7329        synchronized (this) {
7330            ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
7331                    DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
7332            ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
7333            saveSettingsLocked(userHandle);
7334        }
7335    }
7336
7337    @Override
7338    public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
7339            ComponentName agent, int userHandle, boolean parent) {
7340        if (!mHasFeature) {
7341            return null;
7342        }
7343        Preconditions.checkNotNull(agent, "agent null");
7344        enforceFullCrossUsersPermission(userHandle);
7345
7346        synchronized (this) {
7347            final String componentName = agent.flattenToString();
7348            if (admin != null) {
7349                final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
7350                if (ap == null) return null;
7351                TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
7352                if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
7353                List<PersistableBundle> result = new ArrayList<>();
7354                result.add(trustAgentInfo.options);
7355                return result;
7356            }
7357
7358            // Return strictest policy for this user and profiles that are visible from this user.
7359            List<PersistableBundle> result = null;
7360            // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
7361            // of the options. If any admin doesn't have options, discard options for the rest
7362            // and return null.
7363            List<ActiveAdmin> admins =
7364                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
7365            boolean allAdminsHaveOptions = true;
7366            final int N = admins.size();
7367            for (int i = 0; i < N; i++) {
7368                final ActiveAdmin active = admins.get(i);
7369
7370                final boolean disablesTrust = (active.disabledKeyguardFeatures
7371                        & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
7372                final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
7373                if (info != null && info.options != null && !info.options.isEmpty()) {
7374                    if (disablesTrust) {
7375                        if (result == null) {
7376                            result = new ArrayList<>();
7377                        }
7378                        result.add(info.options);
7379                    } else {
7380                        Log.w(LOG_TAG, "Ignoring admin " + active.info
7381                                + " because it has trust options but doesn't declare "
7382                                + "KEYGUARD_DISABLE_TRUST_AGENTS");
7383                    }
7384                } else if (disablesTrust) {
7385                    allAdminsHaveOptions = false;
7386                    break;
7387                }
7388            }
7389            return allAdminsHaveOptions ? result : null;
7390        }
7391    }
7392
7393    @Override
7394    public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
7395        Preconditions.checkNotNull(who, "ComponentName is null");
7396        synchronized (this) {
7397            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7398
7399            int userHandle = UserHandle.getCallingUserId();
7400            DevicePolicyData userData = getUserData(userHandle);
7401            userData.mRestrictionsProvider = permissionProvider;
7402            saveSettingsLocked(userHandle);
7403        }
7404    }
7405
7406    @Override
7407    public ComponentName getRestrictionsProvider(int userHandle) {
7408        synchronized (this) {
7409            if (!isCallerWithSystemUid()) {
7410                throw new SecurityException("Only the system can query the permission provider");
7411            }
7412            DevicePolicyData userData = getUserData(userHandle);
7413            return userData != null ? userData.mRestrictionsProvider : null;
7414        }
7415    }
7416
7417    @Override
7418    public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
7419        Preconditions.checkNotNull(who, "ComponentName is null");
7420        int callingUserId = UserHandle.getCallingUserId();
7421        synchronized (this) {
7422            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7423
7424            long id = mInjector.binderClearCallingIdentity();
7425            try {
7426                UserInfo parent = mUserManager.getProfileParent(callingUserId);
7427                if (parent == null) {
7428                    Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
7429                            + "parent");
7430                    return;
7431                }
7432                if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
7433                    mIPackageManager.addCrossProfileIntentFilter(
7434                            filter, who.getPackageName(), callingUserId, parent.id, 0);
7435                }
7436                if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
7437                    mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
7438                            parent.id, callingUserId, 0);
7439                }
7440            } catch (RemoteException re) {
7441                // Shouldn't happen
7442            } finally {
7443                mInjector.binderRestoreCallingIdentity(id);
7444            }
7445        }
7446    }
7447
7448    @Override
7449    public void clearCrossProfileIntentFilters(ComponentName who) {
7450        Preconditions.checkNotNull(who, "ComponentName is null");
7451        int callingUserId = UserHandle.getCallingUserId();
7452        synchronized (this) {
7453            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7454            long id = mInjector.binderClearCallingIdentity();
7455            try {
7456                UserInfo parent = mUserManager.getProfileParent(callingUserId);
7457                if (parent == null) {
7458                    Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
7459                            + "parent");
7460                    return;
7461                }
7462                // Removing those that go from the managed profile to the parent.
7463                mIPackageManager.clearCrossProfileIntentFilters(
7464                        callingUserId, who.getPackageName());
7465                // And those that go from the parent to the managed profile.
7466                // If we want to support multiple managed profiles, we will have to only remove
7467                // those that have callingUserId as their target.
7468                mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
7469            } catch (RemoteException re) {
7470                // Shouldn't happen
7471            } finally {
7472                mInjector.binderRestoreCallingIdentity(id);
7473            }
7474        }
7475    }
7476
7477    /**
7478     * @return true if all packages in enabledPackages are either in the list
7479     * permittedList or are a system app.
7480     */
7481    private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
7482            List<String> permittedList, int userIdToCheck) {
7483        long id = mInjector.binderClearCallingIdentity();
7484        try {
7485            // If we have an enabled packages list for a managed profile the packages
7486            // we should check are installed for the parent user.
7487            UserInfo user = getUserInfo(userIdToCheck);
7488            if (user.isManagedProfile()) {
7489                userIdToCheck = user.profileGroupId;
7490            }
7491
7492            for (String enabledPackage : enabledPackages) {
7493                boolean systemService = false;
7494                try {
7495                    ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
7496                            enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
7497                            userIdToCheck);
7498                    systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7499                } catch (RemoteException e) {
7500                    Log.i(LOG_TAG, "Can't talk to package managed", e);
7501                }
7502                if (!systemService && !permittedList.contains(enabledPackage)) {
7503                    return false;
7504                }
7505            }
7506        } finally {
7507            mInjector.binderRestoreCallingIdentity(id);
7508        }
7509        return true;
7510    }
7511
7512    private AccessibilityManager getAccessibilityManagerForUser(int userId) {
7513        // Not using AccessibilityManager.getInstance because that guesses
7514        // at the user you require based on callingUid and caches for a given
7515        // process.
7516        IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
7517        IAccessibilityManager service = iBinder == null
7518                ? null : IAccessibilityManager.Stub.asInterface(iBinder);
7519        return new AccessibilityManager(mContext, service, userId);
7520    }
7521
7522    @Override
7523    public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
7524        if (!mHasFeature) {
7525            return false;
7526        }
7527        Preconditions.checkNotNull(who, "ComponentName is null");
7528
7529        if (packageList != null) {
7530            int userId = UserHandle.getCallingUserId();
7531            List<AccessibilityServiceInfo> enabledServices = null;
7532            long id = mInjector.binderClearCallingIdentity();
7533            try {
7534                UserInfo user = getUserInfo(userId);
7535                if (user.isManagedProfile()) {
7536                    userId = user.profileGroupId;
7537                }
7538                AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
7539                enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
7540                        AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
7541            } finally {
7542                mInjector.binderRestoreCallingIdentity(id);
7543            }
7544
7545            if (enabledServices != null) {
7546                List<String> enabledPackages = new ArrayList<String>();
7547                for (AccessibilityServiceInfo service : enabledServices) {
7548                    enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
7549                }
7550                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7551                        userId)) {
7552                    Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
7553                            + "because it contains already enabled accesibility services.");
7554                    return false;
7555                }
7556            }
7557        }
7558
7559        synchronized (this) {
7560            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7561                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7562            admin.permittedAccessiblityServices = packageList;
7563            saveSettingsLocked(UserHandle.getCallingUserId());
7564        }
7565        return true;
7566    }
7567
7568    @Override
7569    public List getPermittedAccessibilityServices(ComponentName who) {
7570        if (!mHasFeature) {
7571            return null;
7572        }
7573        Preconditions.checkNotNull(who, "ComponentName is null");
7574
7575        synchronized (this) {
7576            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7577                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7578            return admin.permittedAccessiblityServices;
7579        }
7580    }
7581
7582    @Override
7583    public List getPermittedAccessibilityServicesForUser(int userId) {
7584        if (!mHasFeature) {
7585            return null;
7586        }
7587        synchronized (this) {
7588            List<String> result = null;
7589            // If we have multiple profiles we return the intersection of the
7590            // permitted lists. This can happen in cases where we have a device
7591            // and profile owner.
7592            int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7593            for (int profileId : profileIds) {
7594                // Just loop though all admins, only device or profiles
7595                // owners can have permitted lists set.
7596                DevicePolicyData policy = getUserDataUnchecked(profileId);
7597                final int N = policy.mAdminList.size();
7598                for (int j = 0; j < N; j++) {
7599                    ActiveAdmin admin = policy.mAdminList.get(j);
7600                    List<String> fromAdmin = admin.permittedAccessiblityServices;
7601                    if (fromAdmin != null) {
7602                        if (result == null) {
7603                            result = new ArrayList<>(fromAdmin);
7604                        } else {
7605                            result.retainAll(fromAdmin);
7606                        }
7607                    }
7608                }
7609            }
7610
7611            // If we have a permitted list add all system accessibility services.
7612            if (result != null) {
7613                long id = mInjector.binderClearCallingIdentity();
7614                try {
7615                    UserInfo user = getUserInfo(userId);
7616                    if (user.isManagedProfile()) {
7617                        userId = user.profileGroupId;
7618                    }
7619                    AccessibilityManager accessibilityManager =
7620                            getAccessibilityManagerForUser(userId);
7621                    List<AccessibilityServiceInfo> installedServices =
7622                            accessibilityManager.getInstalledAccessibilityServiceList();
7623
7624                    if (installedServices != null) {
7625                        for (AccessibilityServiceInfo service : installedServices) {
7626                            ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7627                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7628                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7629                                result.add(serviceInfo.packageName);
7630                            }
7631                        }
7632                    }
7633                } finally {
7634                    mInjector.binderRestoreCallingIdentity(id);
7635                }
7636            }
7637
7638            return result;
7639        }
7640    }
7641
7642    @Override
7643    public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7644            int userHandle) {
7645        if (!mHasFeature) {
7646            return true;
7647        }
7648        Preconditions.checkNotNull(who, "ComponentName is null");
7649        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7650        if (!isCallerWithSystemUid()){
7651            throw new SecurityException(
7652                    "Only the system can query if an accessibility service is disabled by admin");
7653        }
7654        synchronized (this) {
7655            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7656            if (admin == null) {
7657                return false;
7658            }
7659            if (admin.permittedAccessiblityServices == null) {
7660                return true;
7661            }
7662            return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7663                    admin.permittedAccessiblityServices, userHandle);
7664        }
7665    }
7666
7667    private boolean checkCallerIsCurrentUserOrProfile() {
7668        int callingUserId = UserHandle.getCallingUserId();
7669        long token = mInjector.binderClearCallingIdentity();
7670        try {
7671            UserInfo currentUser;
7672            UserInfo callingUser = getUserInfo(callingUserId);
7673            try {
7674                currentUser = mInjector.getIActivityManager().getCurrentUser();
7675            } catch (RemoteException e) {
7676                Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7677                return false;
7678            }
7679
7680            if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7681                Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7682                        + "of a user that isn't the foreground user.");
7683                return false;
7684            }
7685            if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7686                Slog.e(LOG_TAG, "Cannot set permitted input methods "
7687                        + "of a user that isn't the foreground user.");
7688                return false;
7689            }
7690        } finally {
7691            mInjector.binderRestoreCallingIdentity(token);
7692        }
7693        return true;
7694    }
7695
7696    @Override
7697    public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7698        if (!mHasFeature) {
7699            return false;
7700        }
7701        Preconditions.checkNotNull(who, "ComponentName is null");
7702
7703        // TODO When InputMethodManager supports per user calls remove
7704        //      this restriction.
7705        if (!checkCallerIsCurrentUserOrProfile()) {
7706            return false;
7707        }
7708
7709        if (packageList != null) {
7710            // InputMethodManager fetches input methods for current user.
7711            // So this can only be set when calling user is the current user
7712            // or parent is current user in case of managed profiles.
7713            InputMethodManager inputMethodManager =
7714                    mContext.getSystemService(InputMethodManager.class);
7715            List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7716
7717            if (enabledImes != null) {
7718                List<String> enabledPackages = new ArrayList<String>();
7719                for (InputMethodInfo ime : enabledImes) {
7720                    enabledPackages.add(ime.getPackageName());
7721                }
7722                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7723                        mInjector.binderGetCallingUserHandle().getIdentifier())) {
7724                    Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7725                            + "because it contains already enabled input method.");
7726                    return false;
7727                }
7728            }
7729        }
7730
7731        synchronized (this) {
7732            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7733                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7734            admin.permittedInputMethods = packageList;
7735            saveSettingsLocked(UserHandle.getCallingUserId());
7736        }
7737        return true;
7738    }
7739
7740    @Override
7741    public List getPermittedInputMethods(ComponentName who) {
7742        if (!mHasFeature) {
7743            return null;
7744        }
7745        Preconditions.checkNotNull(who, "ComponentName is null");
7746
7747        synchronized (this) {
7748            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7749                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7750            return admin.permittedInputMethods;
7751        }
7752    }
7753
7754    @Override
7755    public List getPermittedInputMethodsForCurrentUser() {
7756        UserInfo currentUser;
7757        try {
7758            currentUser = mInjector.getIActivityManager().getCurrentUser();
7759        } catch (RemoteException e) {
7760            Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7761            // Activity managed is dead, just allow all IMEs
7762            return null;
7763        }
7764
7765        int userId = currentUser.id;
7766        synchronized (this) {
7767            List<String> result = null;
7768            // If we have multiple profiles we return the intersection of the
7769            // permitted lists. This can happen in cases where we have a device
7770            // and profile owner.
7771            int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7772            for (int profileId : profileIds) {
7773                // Just loop though all admins, only device or profiles
7774                // owners can have permitted lists set.
7775                DevicePolicyData policy = getUserDataUnchecked(profileId);
7776                final int N = policy.mAdminList.size();
7777                for (int j = 0; j < N; j++) {
7778                    ActiveAdmin admin = policy.mAdminList.get(j);
7779                    List<String> fromAdmin = admin.permittedInputMethods;
7780                    if (fromAdmin != null) {
7781                        if (result == null) {
7782                            result = new ArrayList<String>(fromAdmin);
7783                        } else {
7784                            result.retainAll(fromAdmin);
7785                        }
7786                    }
7787                }
7788            }
7789
7790            // If we have a permitted list add all system input methods.
7791            if (result != null) {
7792                InputMethodManager inputMethodManager =
7793                        mContext.getSystemService(InputMethodManager.class);
7794                List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7795                long id = mInjector.binderClearCallingIdentity();
7796                try {
7797                    if (imes != null) {
7798                        for (InputMethodInfo ime : imes) {
7799                            ServiceInfo serviceInfo = ime.getServiceInfo();
7800                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7801                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7802                                result.add(serviceInfo.packageName);
7803                            }
7804                        }
7805                    }
7806                } finally {
7807                    mInjector.binderRestoreCallingIdentity(id);
7808                }
7809            }
7810            return result;
7811        }
7812    }
7813
7814    @Override
7815    public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7816            int userHandle) {
7817        if (!mHasFeature) {
7818            return true;
7819        }
7820        Preconditions.checkNotNull(who, "ComponentName is null");
7821        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7822        if (!isCallerWithSystemUid()) {
7823            throw new SecurityException(
7824                    "Only the system can query if an input method is disabled by admin");
7825        }
7826        synchronized (this) {
7827            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7828            if (admin == null) {
7829                return false;
7830            }
7831            if (admin.permittedInputMethods == null) {
7832                return true;
7833            }
7834            return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7835                    admin.permittedInputMethods, userHandle);
7836        }
7837    }
7838
7839    private void sendAdminEnabledBroadcastLocked(int userHandle) {
7840        DevicePolicyData policyData = getUserData(userHandle);
7841        if (policyData.mAdminBroadcastPending) {
7842            // Send the initialization data to profile owner and delete the data
7843            ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7844            if (admin != null) {
7845                PersistableBundle initBundle = policyData.mInitBundle;
7846                sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7847                        initBundle == null ? null : new Bundle(initBundle), null);
7848            }
7849            policyData.mInitBundle = null;
7850            policyData.mAdminBroadcastPending = false;
7851            saveSettingsLocked(userHandle);
7852        }
7853    }
7854
7855    @Override
7856    public UserHandle createAndManageUser(ComponentName admin, String name,
7857            ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7858        Preconditions.checkNotNull(admin, "admin is null");
7859        Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7860        if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7861            throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7862                    + admin + " are not in the same package");
7863        }
7864        // Only allow the system user to use this method
7865        if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7866            throw new SecurityException("createAndManageUser was called from non-system user");
7867        }
7868        if (!mInjector.userManagerIsSplitSystemUser()
7869                && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7870            throw new IllegalArgumentException(
7871                    "Ephemeral users are only supported on systems with a split system user.");
7872        }
7873        // Create user.
7874        UserHandle user = null;
7875        synchronized (this) {
7876            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7877
7878            final long id = mInjector.binderClearCallingIdentity();
7879            try {
7880                int userInfoFlags = 0;
7881                if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7882                    userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7883                }
7884                UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7885                        userInfoFlags);
7886                if (userInfo != null) {
7887                    user = userInfo.getUserHandle();
7888                }
7889            } finally {
7890                mInjector.binderRestoreCallingIdentity(id);
7891            }
7892        }
7893        if (user == null) {
7894            return null;
7895        }
7896        // Set admin.
7897        final long id = mInjector.binderClearCallingIdentity();
7898        try {
7899            final String adminPkg = admin.getPackageName();
7900
7901            final int userHandle = user.getIdentifier();
7902            try {
7903                // Install the profile owner if not present.
7904                if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7905                    mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle,
7906                            PackageManager.INSTALL_REASON_POLICY);
7907                }
7908            } catch (RemoteException e) {
7909                Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7910                        + "removing created user", e);
7911                mUserManager.removeUser(user.getIdentifier());
7912                return null;
7913            }
7914
7915            setActiveAdmin(profileOwner, true, userHandle);
7916            // User is not started yet, the broadcast by setActiveAdmin will not be received.
7917            // So we store adminExtras for broadcasting when the user starts for first time.
7918            synchronized(this) {
7919                DevicePolicyData policyData = getUserData(userHandle);
7920                policyData.mInitBundle = adminExtras;
7921                policyData.mAdminBroadcastPending = true;
7922                saveSettingsLocked(userHandle);
7923            }
7924            final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7925            setProfileOwner(profileOwner, ownerName, userHandle);
7926
7927            if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7928                Settings.Secure.putIntForUser(mContext.getContentResolver(),
7929                        Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7930            }
7931
7932            return user;
7933        } finally {
7934            mInjector.binderRestoreCallingIdentity(id);
7935        }
7936    }
7937
7938    @Override
7939    public boolean removeUser(ComponentName who, UserHandle userHandle) {
7940        Preconditions.checkNotNull(who, "ComponentName is null");
7941        synchronized (this) {
7942            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7943        }
7944
7945        final int callingUserId = mInjector.userHandleGetCallingUserId();
7946        final long id = mInjector.binderClearCallingIdentity();
7947        try {
7948            String restriction = isManagedProfile(userHandle.getIdentifier())
7949                    ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
7950                    : UserManager.DISALLOW_REMOVE_USER;
7951            if (isAdminAffectedByRestriction(who, restriction, callingUserId)) {
7952                Log.w(LOG_TAG, "The device owner cannot remove a user because "
7953                        + restriction + " is enabled, and was not set by the device owner");
7954                return false;
7955            }
7956            return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
7957        } finally {
7958            mInjector.binderRestoreCallingIdentity(id);
7959        }
7960    }
7961
7962    private boolean isAdminAffectedByRestriction(
7963            ComponentName admin, String userRestriction, int userId) {
7964        switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
7965            case UserManager.RESTRICTION_NOT_SET:
7966                return false;
7967            case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
7968                return !isDeviceOwner(admin, userId);
7969            case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
7970                return !isProfileOwner(admin, userId);
7971            default:
7972                return true;
7973        }
7974    }
7975
7976    @Override
7977    public boolean switchUser(ComponentName who, UserHandle userHandle) {
7978        Preconditions.checkNotNull(who, "ComponentName is null");
7979        synchronized (this) {
7980            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7981
7982            long id = mInjector.binderClearCallingIdentity();
7983            try {
7984                int userId = UserHandle.USER_SYSTEM;
7985                if (userHandle != null) {
7986                    userId = userHandle.getIdentifier();
7987                }
7988                return mInjector.getIActivityManager().switchUser(userId);
7989            } catch (RemoteException e) {
7990                Log.e(LOG_TAG, "Couldn't switch user", e);
7991                return false;
7992            } finally {
7993                mInjector.binderRestoreCallingIdentity(id);
7994            }
7995        }
7996    }
7997
7998    @Override
7999    public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
8000            String packageName) {
8001        enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8002                DELEGATION_APP_RESTRICTIONS);
8003
8004        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
8005        final long id = mInjector.binderClearCallingIdentity();
8006        try {
8007           Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
8008           // if no restrictions were saved, mUserManager.getApplicationRestrictions
8009           // returns null, but DPM method should return an empty Bundle as per JavaDoc
8010           return bundle != null ? bundle : Bundle.EMPTY;
8011        } finally {
8012            mInjector.binderRestoreCallingIdentity(id);
8013        }
8014    }
8015
8016    @Override
8017    public String[] setPackagesSuspended(ComponentName who, String callerPackage,
8018            String[] packageNames, boolean suspended) {
8019        int callingUserId = UserHandle.getCallingUserId();
8020        synchronized (this) {
8021            // Ensure the caller is a DO/PO or a package access delegate.
8022            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8023                    DELEGATION_PACKAGE_ACCESS);
8024
8025            long id = mInjector.binderClearCallingIdentity();
8026            try {
8027                return mIPackageManager.setPackagesSuspendedAsUser(
8028                        packageNames, suspended, callingUserId);
8029            } catch (RemoteException re) {
8030                // Shouldn't happen.
8031                Slog.e(LOG_TAG, "Failed talking to the package manager", re);
8032            } finally {
8033                mInjector.binderRestoreCallingIdentity(id);
8034            }
8035            return packageNames;
8036        }
8037    }
8038
8039    @Override
8040    public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
8041        int callingUserId = UserHandle.getCallingUserId();
8042        synchronized (this) {
8043            // Ensure the caller is a DO/PO or a package access delegate.
8044            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8045                    DELEGATION_PACKAGE_ACCESS);
8046            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8047
8048            long id = mInjector.binderClearCallingIdentity();
8049            try {
8050                return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
8051            } catch (RemoteException re) {
8052                // Shouldn't happen.
8053                Slog.e(LOG_TAG, "Failed talking to the package manager", re);
8054            } finally {
8055                mInjector.binderRestoreCallingIdentity(id);
8056            }
8057            return false;
8058        }
8059    }
8060
8061    @Override
8062    public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
8063        Preconditions.checkNotNull(who, "ComponentName is null");
8064        if (!UserRestrictionsUtils.isValidRestriction(key)) {
8065            return;
8066        }
8067
8068        final int userHandle = mInjector.userHandleGetCallingUserId();
8069        synchronized (this) {
8070            final ActiveAdmin activeAdmin =
8071                    getActiveAdminForCallerLocked(who,
8072                            DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8073            final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
8074            if (isDeviceOwner) {
8075                if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
8076                    throw new SecurityException("Device owner cannot set user restriction " + key);
8077                }
8078            } else { // profile owner
8079                if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
8080                    throw new SecurityException("Profile owner cannot set user restriction " + key);
8081                }
8082            }
8083
8084            // Save the restriction to ActiveAdmin.
8085            final Bundle restrictions = activeAdmin.ensureUserRestrictions();
8086            if (enabledFromThisOwner) {
8087                restrictions.putBoolean(key, true);
8088            } else {
8089                restrictions.remove(key);
8090            }
8091            saveUserRestrictionsLocked(userHandle);
8092        }
8093    }
8094
8095    private void saveUserRestrictionsLocked(int userId) {
8096        saveSettingsLocked(userId);
8097        pushUserRestrictions(userId);
8098        sendChangedNotification(userId);
8099    }
8100
8101    private void pushUserRestrictions(int userId) {
8102        synchronized (this) {
8103            final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId);
8104            final Bundle userRestrictions;
8105            // Whether device owner enforces camera restriction.
8106            boolean disallowCameraGlobally = false;
8107
8108            if (isDeviceOwner) {
8109                final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
8110                if (deviceOwner == null) {
8111                    return; // Shouldn't happen.
8112                }
8113                userRestrictions = deviceOwner.userRestrictions;
8114                // DO can disable camera globally.
8115                disallowCameraGlobally = deviceOwner.disableCamera;
8116            } else {
8117                final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
8118                userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null;
8119            }
8120
8121            // Whether any admin enforces camera restriction.
8122            final int cameraRestrictionScope =
8123                    getCameraRestrictionScopeLocked(userId, disallowCameraGlobally);
8124
8125            mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions,
8126                    isDeviceOwner, cameraRestrictionScope);
8127        }
8128    }
8129
8130    /**
8131     * Get the scope of camera restriction for a given user if any.
8132     */
8133    private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) {
8134        if (disallowCameraGlobally) {
8135            return UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
8136        } else if (getCameraDisabled(
8137                /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) {
8138            return UserManagerInternal.CAMERA_DISABLED_LOCALLY;
8139        }
8140        return UserManagerInternal.CAMERA_NOT_DISABLED;
8141    }
8142
8143    @Override
8144    public Bundle getUserRestrictions(ComponentName who) {
8145        if (!mHasFeature) {
8146            return null;
8147        }
8148        Preconditions.checkNotNull(who, "ComponentName is null");
8149        synchronized (this) {
8150            final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
8151                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8152            return activeAdmin.userRestrictions;
8153        }
8154    }
8155
8156    @Override
8157    public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
8158            boolean hidden) {
8159        int callingUserId = UserHandle.getCallingUserId();
8160        synchronized (this) {
8161            // Ensure the caller is a DO/PO or a package access delegate.
8162            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8163                    DELEGATION_PACKAGE_ACCESS);
8164
8165            long id = mInjector.binderClearCallingIdentity();
8166            try {
8167                return mIPackageManager.setApplicationHiddenSettingAsUser(
8168                        packageName, hidden, callingUserId);
8169            } catch (RemoteException re) {
8170                // shouldn't happen
8171                Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
8172            } finally {
8173                mInjector.binderRestoreCallingIdentity(id);
8174            }
8175            return false;
8176        }
8177    }
8178
8179    @Override
8180    public boolean isApplicationHidden(ComponentName who, String callerPackage,
8181            String packageName) {
8182        int callingUserId = UserHandle.getCallingUserId();
8183        synchronized (this) {
8184            // Ensure the caller is a DO/PO or a package access delegate.
8185            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8186                    DELEGATION_PACKAGE_ACCESS);
8187
8188            long id = mInjector.binderClearCallingIdentity();
8189            try {
8190                return mIPackageManager.getApplicationHiddenSettingAsUser(
8191                        packageName, callingUserId);
8192            } catch (RemoteException re) {
8193                // shouldn't happen
8194                Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
8195            } finally {
8196                mInjector.binderRestoreCallingIdentity(id);
8197            }
8198            return false;
8199        }
8200    }
8201
8202    @Override
8203    public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
8204        synchronized (this) {
8205            // Ensure the caller is a DO/PO or an enable system app delegate.
8206            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8207                    DELEGATION_ENABLE_SYSTEM_APP);
8208
8209            int userId = UserHandle.getCallingUserId();
8210            long id = mInjector.binderClearCallingIdentity();
8211
8212            try {
8213                if (VERBOSE_LOG) {
8214                    Slog.v(LOG_TAG, "installing " + packageName + " for "
8215                            + userId);
8216                }
8217
8218                int parentUserId = getProfileParentId(userId);
8219                if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
8220                    throw new IllegalArgumentException("Only system apps can be enabled this way.");
8221                }
8222
8223                // Install the app.
8224                mIPackageManager.installExistingPackageAsUser(packageName, userId,
8225                        PackageManager.INSTALL_REASON_POLICY);
8226
8227            } catch (RemoteException re) {
8228                // shouldn't happen
8229                Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
8230            } finally {
8231                mInjector.binderRestoreCallingIdentity(id);
8232            }
8233        }
8234    }
8235
8236    @Override
8237    public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
8238        synchronized (this) {
8239            // Ensure the caller is a DO/PO or an enable system app delegate.
8240            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8241                    DELEGATION_ENABLE_SYSTEM_APP);
8242
8243            int userId = UserHandle.getCallingUserId();
8244            long id = mInjector.binderClearCallingIdentity();
8245
8246            try {
8247                int parentUserId = getProfileParentId(userId);
8248                List<ResolveInfo> activitiesToEnable = mIPackageManager
8249                        .queryIntentActivities(intent,
8250                                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
8251                                PackageManager.MATCH_DIRECT_BOOT_AWARE
8252                                        | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
8253                                parentUserId)
8254                        .getList();
8255
8256                if (VERBOSE_LOG) {
8257                    Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
8258                }
8259                int numberOfAppsInstalled = 0;
8260                if (activitiesToEnable != null) {
8261                    for (ResolveInfo info : activitiesToEnable) {
8262                        if (info.activityInfo != null) {
8263                            String packageName = info.activityInfo.packageName;
8264                            if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
8265                                numberOfAppsInstalled++;
8266                                mIPackageManager.installExistingPackageAsUser(packageName, userId,
8267                                        PackageManager.INSTALL_REASON_POLICY);
8268                            } else {
8269                                Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
8270                                        + " system app");
8271                            }
8272                        }
8273                    }
8274                }
8275                return numberOfAppsInstalled;
8276            } catch (RemoteException e) {
8277                // shouldn't happen
8278                Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
8279                return 0;
8280            } finally {
8281                mInjector.binderRestoreCallingIdentity(id);
8282            }
8283        }
8284    }
8285
8286    private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
8287            throws RemoteException {
8288        ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
8289                userId);
8290        if (appInfo == null) {
8291            throw new IllegalArgumentException("The application " + packageName +
8292                    " is not present on this device");
8293        }
8294        return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
8295    }
8296
8297    @Override
8298    public void setAccountManagementDisabled(ComponentName who, String accountType,
8299            boolean disabled) {
8300        if (!mHasFeature) {
8301            return;
8302        }
8303        Preconditions.checkNotNull(who, "ComponentName is null");
8304        synchronized (this) {
8305            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
8306                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8307            if (disabled) {
8308                ap.accountTypesWithManagementDisabled.add(accountType);
8309            } else {
8310                ap.accountTypesWithManagementDisabled.remove(accountType);
8311            }
8312            saveSettingsLocked(UserHandle.getCallingUserId());
8313        }
8314    }
8315
8316    @Override
8317    public String[] getAccountTypesWithManagementDisabled() {
8318        return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
8319    }
8320
8321    @Override
8322    public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
8323        enforceFullCrossUsersPermission(userId);
8324        if (!mHasFeature) {
8325            return null;
8326        }
8327        synchronized (this) {
8328            DevicePolicyData policy = getUserData(userId);
8329            final int N = policy.mAdminList.size();
8330            ArraySet<String> resultSet = new ArraySet<>();
8331            for (int i = 0; i < N; i++) {
8332                ActiveAdmin admin = policy.mAdminList.get(i);
8333                resultSet.addAll(admin.accountTypesWithManagementDisabled);
8334            }
8335            return resultSet.toArray(new String[resultSet.size()]);
8336        }
8337    }
8338
8339    @Override
8340    public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
8341            boolean uninstallBlocked) {
8342        final int userId = UserHandle.getCallingUserId();
8343        synchronized (this) {
8344            // Ensure the caller is a DO/PO or a block uninstall delegate
8345            enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8346                    DELEGATION_BLOCK_UNINSTALL);
8347
8348            long id = mInjector.binderClearCallingIdentity();
8349            try {
8350                mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
8351            } catch (RemoteException re) {
8352                // Shouldn't happen.
8353                Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
8354            } finally {
8355                mInjector.binderRestoreCallingIdentity(id);
8356            }
8357        }
8358    }
8359
8360    @Override
8361    public boolean isUninstallBlocked(ComponentName who, String packageName) {
8362        // This function should return true if and only if the package is blocked by
8363        // setUninstallBlocked(). It should still return false for other cases of blocks, such as
8364        // when the package is a system app, or when it is an active device admin.
8365        final int userId = UserHandle.getCallingUserId();
8366
8367        synchronized (this) {
8368            if (who != null) {
8369                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8370            }
8371
8372            long id = mInjector.binderClearCallingIdentity();
8373            try {
8374                return mIPackageManager.getBlockUninstallForUser(packageName, userId);
8375            } catch (RemoteException re) {
8376                // Shouldn't happen.
8377                Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
8378            } finally {
8379                mInjector.binderRestoreCallingIdentity(id);
8380            }
8381        }
8382        return false;
8383    }
8384
8385    @Override
8386    public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
8387        if (!mHasFeature) {
8388            return;
8389        }
8390        Preconditions.checkNotNull(who, "ComponentName is null");
8391        synchronized (this) {
8392            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8393                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8394            if (admin.disableCallerId != disabled) {
8395                admin.disableCallerId = disabled;
8396                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
8397            }
8398        }
8399    }
8400
8401    @Override
8402    public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
8403        if (!mHasFeature) {
8404            return false;
8405        }
8406        Preconditions.checkNotNull(who, "ComponentName is null");
8407        synchronized (this) {
8408            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8409                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8410            return admin.disableCallerId;
8411        }
8412    }
8413
8414    @Override
8415    public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
8416        enforceCrossUsersPermission(userId);
8417        synchronized (this) {
8418            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8419            return (admin != null) ? admin.disableCallerId : false;
8420        }
8421    }
8422
8423    @Override
8424    public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
8425        if (!mHasFeature) {
8426            return;
8427        }
8428        Preconditions.checkNotNull(who, "ComponentName is null");
8429        synchronized (this) {
8430            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8431                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8432            if (admin.disableContactsSearch != disabled) {
8433                admin.disableContactsSearch = disabled;
8434                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
8435            }
8436        }
8437    }
8438
8439    @Override
8440    public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
8441        if (!mHasFeature) {
8442            return false;
8443        }
8444        Preconditions.checkNotNull(who, "ComponentName is null");
8445        synchronized (this) {
8446            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8447                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8448            return admin.disableContactsSearch;
8449        }
8450    }
8451
8452    @Override
8453    public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
8454        enforceCrossUsersPermission(userId);
8455        synchronized (this) {
8456            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8457            return (admin != null) ? admin.disableContactsSearch : false;
8458        }
8459    }
8460
8461    @Override
8462    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
8463            boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
8464        final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
8465                actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
8466        final int callingUserId = UserHandle.getCallingUserId();
8467
8468        final long ident = mInjector.binderClearCallingIdentity();
8469        try {
8470            synchronized (this) {
8471                final int managedUserId = getManagedUserId(callingUserId);
8472                if (managedUserId < 0) {
8473                    return;
8474                }
8475                if (isCrossProfileQuickContactDisabled(managedUserId)) {
8476                    if (VERBOSE_LOG) {
8477                        Log.v(LOG_TAG,
8478                                "Cross-profile contacts access disabled for user " + managedUserId);
8479                    }
8480                    return;
8481                }
8482                ContactsInternal.startQuickContactWithErrorToastForUser(
8483                        mContext, intent, new UserHandle(managedUserId));
8484            }
8485        } finally {
8486            mInjector.binderRestoreCallingIdentity(ident);
8487        }
8488    }
8489
8490    /**
8491     * @return true if cross-profile QuickContact is disabled
8492     */
8493    private boolean isCrossProfileQuickContactDisabled(int userId) {
8494        return getCrossProfileCallerIdDisabledForUser(userId)
8495                && getCrossProfileContactsSearchDisabledForUser(userId);
8496    }
8497
8498    /**
8499     * @return the user ID of the managed user that is linked to the current user, if any.
8500     * Otherwise -1.
8501     */
8502    public int getManagedUserId(int callingUserId) {
8503        if (VERBOSE_LOG) {
8504            Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
8505        }
8506
8507        for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
8508            if (ui.id == callingUserId || !ui.isManagedProfile()) {
8509                continue; // Caller user self, or not a managed profile.  Skip.
8510            }
8511            if (VERBOSE_LOG) {
8512                Log.v(LOG_TAG, "Managed user=" + ui.id);
8513            }
8514            return ui.id;
8515        }
8516        if (VERBOSE_LOG) {
8517            Log.v(LOG_TAG, "Managed user not found.");
8518        }
8519        return -1;
8520    }
8521
8522    @Override
8523    public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
8524        if (!mHasFeature) {
8525            return;
8526        }
8527        Preconditions.checkNotNull(who, "ComponentName is null");
8528        synchronized (this) {
8529            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8530                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8531            if (admin.disableBluetoothContactSharing != disabled) {
8532                admin.disableBluetoothContactSharing = disabled;
8533                saveSettingsLocked(UserHandle.getCallingUserId());
8534            }
8535        }
8536    }
8537
8538    @Override
8539    public boolean getBluetoothContactSharingDisabled(ComponentName who) {
8540        if (!mHasFeature) {
8541            return false;
8542        }
8543        Preconditions.checkNotNull(who, "ComponentName is null");
8544        synchronized (this) {
8545            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8546                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8547            return admin.disableBluetoothContactSharing;
8548        }
8549    }
8550
8551    @Override
8552    public boolean getBluetoothContactSharingDisabledForUser(int userId) {
8553        // TODO: Should there be a check to make sure this relationship is
8554        // within a profile group?
8555        // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
8556        synchronized (this) {
8557            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8558            return (admin != null) ? admin.disableBluetoothContactSharing : false;
8559        }
8560    }
8561
8562    /**
8563     * Sets which packages may enter lock task mode.
8564     *
8565     * <p>This function can only be called by the device owner or alternatively by the profile owner
8566     * in case the user is affiliated.
8567     *
8568     * @param packages The list of packages allowed to enter lock task mode.
8569     */
8570    @Override
8571    public void setLockTaskPackages(ComponentName who, String[] packages)
8572            throws SecurityException {
8573        Preconditions.checkNotNull(who, "ComponentName is null");
8574
8575        synchronized (this) {
8576            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8577            final int userHandle = mInjector.userHandleGetCallingUserId();
8578            if (isUserAffiliatedWithDeviceLocked(userHandle)) {
8579                setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
8580            } else {
8581                throw new SecurityException("Admin " + who +
8582                    " is neither the device owner or affiliated user's profile owner.");
8583            }
8584        }
8585    }
8586
8587    private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
8588        DevicePolicyData policy = getUserData(userHandle);
8589        policy.mLockTaskPackages = packages;
8590
8591        // Store the settings persistently.
8592        saveSettingsLocked(userHandle);
8593        updateLockTaskPackagesLocked(packages, userHandle);
8594    }
8595
8596    /**
8597     * This function returns the list of components allowed to start the task lock mode.
8598     */
8599    @Override
8600    public String[] getLockTaskPackages(ComponentName who) {
8601        Preconditions.checkNotNull(who, "ComponentName is null");
8602        synchronized (this) {
8603            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8604            int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
8605            final List<String> packages = getLockTaskPackagesLocked(userHandle);
8606            return packages.toArray(new String[packages.size()]);
8607        }
8608    }
8609
8610    private List<String> getLockTaskPackagesLocked(int userHandle) {
8611        final DevicePolicyData policy = getUserData(userHandle);
8612        return policy.mLockTaskPackages;
8613    }
8614
8615    /**
8616     * This function lets the caller know whether the given package is allowed to start the
8617     * lock task mode.
8618     * @param pkg The package to check
8619     */
8620    @Override
8621    public boolean isLockTaskPermitted(String pkg) {
8622        // Get current user's devicepolicy
8623        int uid = mInjector.binderGetCallingUid();
8624        int userHandle = UserHandle.getUserId(uid);
8625        DevicePolicyData policy = getUserData(userHandle);
8626        synchronized (this) {
8627            for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
8628                String lockTaskPackage = policy.mLockTaskPackages.get(i);
8629
8630                // If the given package equals one of the packages stored our list,
8631                // we allow this package to start lock task mode.
8632                if (lockTaskPackage.equals(pkg)) {
8633                    return true;
8634                }
8635            }
8636        }
8637        return false;
8638    }
8639
8640    @Override
8641    public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
8642        if (!isCallerWithSystemUid()) {
8643            throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
8644        }
8645        synchronized (this) {
8646            final DevicePolicyData policy = getUserData(userHandle);
8647            Bundle adminExtras = new Bundle();
8648            adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
8649            for (ActiveAdmin admin : policy.mAdminList) {
8650                final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
8651                final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
8652                if (ownsDevice || ownsProfile) {
8653                    if (isEnabled) {
8654                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
8655                                adminExtras, null);
8656                    } else {
8657                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
8658                    }
8659                }
8660            }
8661        }
8662    }
8663
8664    @Override
8665    public void setGlobalSetting(ComponentName who, String setting, String value) {
8666        Preconditions.checkNotNull(who, "ComponentName is null");
8667
8668        synchronized (this) {
8669            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8670
8671            // Some settings are no supported any more. However we do not want to throw a
8672            // SecurityException to avoid breaking apps.
8673            if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
8674                Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
8675                return;
8676            }
8677
8678            if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
8679                throw new SecurityException(String.format(
8680                        "Permission denial: device owners cannot update %1$s", setting));
8681            }
8682
8683            if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
8684                // ignore if it contradicts an existing policy
8685                long timeMs = getMaximumTimeToLock(
8686                        who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
8687                if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
8688                    return;
8689                }
8690            }
8691
8692            long id = mInjector.binderClearCallingIdentity();
8693            try {
8694                mInjector.settingsGlobalPutString(setting, value);
8695            } finally {
8696                mInjector.binderRestoreCallingIdentity(id);
8697            }
8698        }
8699    }
8700
8701    @Override
8702    public void setSecureSetting(ComponentName who, String setting, String value) {
8703        Preconditions.checkNotNull(who, "ComponentName is null");
8704        int callingUserId = mInjector.userHandleGetCallingUserId();
8705
8706        synchronized (this) {
8707            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8708
8709            if (isDeviceOwner(who, callingUserId)) {
8710                if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
8711                    throw new SecurityException(String.format(
8712                            "Permission denial: Device owners cannot update %1$s", setting));
8713                }
8714            } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
8715                throw new SecurityException(String.format(
8716                        "Permission denial: Profile owners cannot update %1$s", setting));
8717            }
8718
8719            long id = mInjector.binderClearCallingIdentity();
8720            try {
8721                mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
8722            } finally {
8723                mInjector.binderRestoreCallingIdentity(id);
8724            }
8725        }
8726    }
8727
8728    @Override
8729    public void setMasterVolumeMuted(ComponentName who, boolean on) {
8730        Preconditions.checkNotNull(who, "ComponentName is null");
8731        synchronized (this) {
8732            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8733            setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
8734        }
8735    }
8736
8737    @Override
8738    public boolean isMasterVolumeMuted(ComponentName who) {
8739        Preconditions.checkNotNull(who, "ComponentName is null");
8740        synchronized (this) {
8741            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8742
8743            AudioManager audioManager =
8744                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
8745            return audioManager.isMasterMute();
8746        }
8747    }
8748
8749    @Override
8750    public void setUserIcon(ComponentName who, Bitmap icon) {
8751        synchronized (this) {
8752            Preconditions.checkNotNull(who, "ComponentName is null");
8753            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8754
8755            int userId = UserHandle.getCallingUserId();
8756            long id = mInjector.binderClearCallingIdentity();
8757            try {
8758                mUserManagerInternal.setUserIcon(userId, icon);
8759            } finally {
8760                mInjector.binderRestoreCallingIdentity(id);
8761            }
8762        }
8763    }
8764
8765    @Override
8766    public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8767        Preconditions.checkNotNull(who, "ComponentName is null");
8768        synchronized (this) {
8769            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8770        }
8771        final int userId = UserHandle.getCallingUserId();
8772
8773        long ident = mInjector.binderClearCallingIdentity();
8774        try {
8775            // disallow disabling the keyguard if a password is currently set
8776            if (disabled && mLockPatternUtils.isSecure(userId)) {
8777                return false;
8778            }
8779            mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8780        } finally {
8781            mInjector.binderRestoreCallingIdentity(ident);
8782        }
8783        return true;
8784    }
8785
8786    @Override
8787    public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8788        int userId = UserHandle.getCallingUserId();
8789        synchronized (this) {
8790            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8791            DevicePolicyData policy = getUserData(userId);
8792            if (policy.mStatusBarDisabled != disabled) {
8793                if (!setStatusBarDisabledInternal(disabled, userId)) {
8794                    return false;
8795                }
8796                policy.mStatusBarDisabled = disabled;
8797                saveSettingsLocked(userId);
8798            }
8799        }
8800        return true;
8801    }
8802
8803    private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8804        long ident = mInjector.binderClearCallingIdentity();
8805        try {
8806            IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8807                    ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8808            if (statusBarService != null) {
8809                int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8810                int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8811                statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8812                statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8813                return true;
8814            }
8815        } catch (RemoteException e) {
8816            Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8817        } finally {
8818            mInjector.binderRestoreCallingIdentity(ident);
8819        }
8820        return false;
8821    }
8822
8823    /**
8824     * We need to update the internal state of whether a user has completed setup or a
8825     * device has paired once. After that, we ignore any changes that reset the
8826     * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
8827     * as we don't trust any apps that might try to reset them.
8828     * <p>
8829     * Unfortunately, we don't know which user's setup state was changed, so we write all of
8830     * them.
8831     */
8832    void updateUserSetupCompleteAndPaired() {
8833        List<UserInfo> users = mUserManager.getUsers(true);
8834        final int N = users.size();
8835        for (int i = 0; i < N; i++) {
8836            int userHandle = users.get(i).id;
8837            if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8838                    userHandle) != 0) {
8839                DevicePolicyData policy = getUserData(userHandle);
8840                if (!policy.mUserSetupComplete) {
8841                    policy.mUserSetupComplete = true;
8842                    synchronized (this) {
8843                        saveSettingsLocked(userHandle);
8844                    }
8845                }
8846            }
8847            if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
8848                    userHandle) != 0) {
8849                DevicePolicyData policy = getUserData(userHandle);
8850                if (!policy.mPaired) {
8851                    policy.mPaired = true;
8852                    synchronized (this) {
8853                        saveSettingsLocked(userHandle);
8854                    }
8855                }
8856            }
8857        }
8858    }
8859
8860    private class SetupContentObserver extends ContentObserver {
8861
8862        private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8863                Settings.Secure.USER_SETUP_COMPLETE);
8864        private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8865                Settings.Global.DEVICE_PROVISIONED);
8866        private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
8867
8868        public SetupContentObserver(Handler handler) {
8869            super(handler);
8870        }
8871
8872        void register() {
8873            mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8874            mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8875            if (mIsWatch) {
8876                mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
8877            }
8878        }
8879
8880        @Override
8881        public void onChange(boolean selfChange, Uri uri) {
8882            if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
8883                updateUserSetupCompleteAndPaired();
8884            } else if (mDeviceProvisioned.equals(uri)) {
8885                synchronized (DevicePolicyManagerService.this) {
8886                    // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8887                    // is delayed until device is marked as provisioned.
8888                    setDeviceOwnerSystemPropertyLocked();
8889                }
8890            }
8891        }
8892    }
8893
8894    @VisibleForTesting
8895    final class LocalService extends DevicePolicyManagerInternal {
8896        private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8897
8898        @Override
8899        public List<String> getCrossProfileWidgetProviders(int profileId) {
8900            synchronized (DevicePolicyManagerService.this) {
8901                if (mOwners == null) {
8902                    return Collections.emptyList();
8903                }
8904                ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8905                if (ownerComponent == null) {
8906                    return Collections.emptyList();
8907                }
8908
8909                DevicePolicyData policy = getUserDataUnchecked(profileId);
8910                ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8911
8912                if (admin == null || admin.crossProfileWidgetProviders == null
8913                        || admin.crossProfileWidgetProviders.isEmpty()) {
8914                    return Collections.emptyList();
8915                }
8916
8917                return admin.crossProfileWidgetProviders;
8918            }
8919        }
8920
8921        @Override
8922        public void addOnCrossProfileWidgetProvidersChangeListener(
8923                OnCrossProfileWidgetProvidersChangeListener listener) {
8924            synchronized (DevicePolicyManagerService.this) {
8925                if (mWidgetProviderListeners == null) {
8926                    mWidgetProviderListeners = new ArrayList<>();
8927                }
8928                if (!mWidgetProviderListeners.contains(listener)) {
8929                    mWidgetProviderListeners.add(listener);
8930                }
8931            }
8932        }
8933
8934        @Override
8935        public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8936            synchronized(DevicePolicyManagerService.this) {
8937                return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8938            }
8939        }
8940
8941        private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8942            final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8943            synchronized (DevicePolicyManagerService.this) {
8944                listeners = new ArrayList<>(mWidgetProviderListeners);
8945            }
8946            final int listenerCount = listeners.size();
8947            for (int i = 0; i < listenerCount; i++) {
8948                OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8949                listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8950            }
8951        }
8952
8953        @Override
8954        public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
8955            // This method is called from AM with its lock held, so don't take the DPMS lock.
8956            // b/29242568
8957
8958            ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8959            if (profileOwner != null) {
8960                return DevicePolicyManagerService.this
8961                        .createShowAdminSupportIntent(profileOwner, userId);
8962            }
8963
8964            final Pair<Integer, ComponentName> deviceOwner =
8965                    mOwners.getDeviceOwnerUserIdAndComponent();
8966            if (deviceOwner != null && deviceOwner.first == userId) {
8967                return DevicePolicyManagerService.this
8968                        .createShowAdminSupportIntent(deviceOwner.second, userId);
8969            }
8970
8971            // We're not specifying the device admin because there isn't one.
8972            if (useDefaultIfNoAdmin) {
8973                return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
8974            }
8975            return null;
8976        }
8977
8978        @Override
8979        public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
8980            int source;
8981            long ident = mInjector.binderClearCallingIdentity();
8982            try {
8983                source = mUserManager.getUserRestrictionSource(userRestriction,
8984                        UserHandle.of(userId));
8985            } finally {
8986                mInjector.binderRestoreCallingIdentity(ident);
8987            }
8988            if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) {
8989                /*
8990                 * In this case, the user restriction is enforced by the system.
8991                 * So we won't show an admin support intent, even if it is also
8992                 * enforced by a profile/device owner.
8993                 */
8994                return null;
8995            }
8996            boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0;
8997            boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0;
8998            if (enforcedByDo && enforcedByPo) {
8999                // In this case, we'll show an admin support dialog that does not
9000                // specify the admin.
9001                return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
9002            } else if (enforcedByPo) {
9003                final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
9004                if (profileOwner != null) {
9005                    return DevicePolicyManagerService.this
9006                            .createShowAdminSupportIntent(profileOwner, userId);
9007                }
9008                // This could happen if another thread has changed the profile owner since we called
9009                // getUserRestrictionSource
9010                return null;
9011            } else if (enforcedByDo) {
9012                final Pair<Integer, ComponentName> deviceOwner
9013                        = mOwners.getDeviceOwnerUserIdAndComponent();
9014                if (deviceOwner != null) {
9015                    return DevicePolicyManagerService.this
9016                            .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first);
9017                }
9018                // This could happen if another thread has changed the device owner since we called
9019                // getUserRestrictionSource
9020                return null;
9021            }
9022            return null;
9023        }
9024    }
9025
9026    private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
9027        // This method is called with AMS lock held, so don't take DPMS lock
9028        final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
9029        intent.putExtra(Intent.EXTRA_USER_ID, userId);
9030        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
9031        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9032        return intent;
9033    }
9034
9035    @Override
9036    public Intent createAdminSupportIntent(String restriction) {
9037        Preconditions.checkNotNull(restriction);
9038        final int uid = mInjector.binderGetCallingUid();
9039        final int userId = UserHandle.getUserId(uid);
9040        Intent intent = null;
9041        if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) ||
9042                DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
9043            synchronized(this) {
9044                final DevicePolicyData policy = getUserData(userId);
9045                final int N = policy.mAdminList.size();
9046                for (int i = 0; i < N; i++) {
9047                    final ActiveAdmin admin = policy.mAdminList.get(i);
9048                    if ((admin.disableCamera &&
9049                                DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) ||
9050                        (admin.disableScreenCapture && DevicePolicyManager
9051                                .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) {
9052                        intent = createShowAdminSupportIntent(admin.info.getComponent(), userId);
9053                        break;
9054                    }
9055                }
9056                // For the camera, a device owner on a different user can disable it globally,
9057                // so we need an additional check.
9058                if (intent == null
9059                        && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
9060                    final ActiveAdmin admin = getDeviceOwnerAdminLocked();
9061                    if (admin != null && admin.disableCamera) {
9062                        intent = createShowAdminSupportIntent(admin.info.getComponent(),
9063                                mOwners.getDeviceOwnerUserId());
9064                    }
9065                }
9066            }
9067        } else {
9068            // if valid, |restriction| can only be a user restriction
9069            intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction);
9070        }
9071        if (intent != null) {
9072            intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
9073        }
9074        return intent;
9075    }
9076
9077    /**
9078     * Returns true if specified admin is allowed to limit passwords and has a
9079     * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
9080     */
9081    private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
9082        if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
9083            return false;
9084        }
9085        return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
9086    }
9087
9088    @Override
9089    public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
9090        if (policy != null && !policy.isValid()) {
9091            throw new IllegalArgumentException("Invalid system update policy.");
9092        }
9093        synchronized (this) {
9094            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9095            if (policy == null) {
9096                mOwners.clearSystemUpdatePolicy();
9097            } else {
9098                mOwners.setSystemUpdatePolicy(policy);
9099            }
9100            mOwners.writeDeviceOwner();
9101        }
9102        mContext.sendBroadcastAsUser(
9103                new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
9104                UserHandle.SYSTEM);
9105    }
9106
9107    @Override
9108    public SystemUpdatePolicy getSystemUpdatePolicy() {
9109        if (UserManager.isDeviceInDemoMode(mContext)) {
9110            // Pretending to have an automatic update policy when the device is in retail demo
9111            // mode. This will allow the device to download and install an ota without
9112            // any user interaction.
9113            return SystemUpdatePolicy.createAutomaticInstallPolicy();
9114        }
9115        synchronized (this) {
9116            SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
9117            if (policy != null && !policy.isValid()) {
9118                Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
9119                return null;
9120            }
9121            return policy;
9122        }
9123    }
9124
9125    /**
9126     * Checks if the caller of the method is the device owner app.
9127     *
9128     * @param callerUid UID of the caller.
9129     * @return true if the caller is the device owner app
9130     */
9131    @VisibleForTesting
9132    boolean isCallerDeviceOwner(int callerUid) {
9133        synchronized (this) {
9134            if (!mOwners.hasDeviceOwner()) {
9135                return false;
9136            }
9137            if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
9138                return false;
9139            }
9140            final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
9141                    .getPackageName();
9142            final String[] pkgs = mInjector.getPackageManager().getPackagesForUid(callerUid);
9143
9144            for (String pkg : pkgs) {
9145                if (deviceOwnerPackageName.equals(pkg)) {
9146                    return true;
9147                }
9148            }
9149        }
9150
9151        return false;
9152    }
9153
9154    @Override
9155    public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
9156        mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
9157                "Only the system update service can broadcast update information");
9158
9159        if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
9160            Slog.w(LOG_TAG, "Only the system update service in the system user " +
9161                    "can broadcast update information.");
9162            return;
9163        }
9164
9165        if (!mOwners.saveSystemUpdateInfo(info)) {
9166            // Pending system update hasn't changed, don't send duplicate notification.
9167            return;
9168        }
9169
9170        final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
9171                .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
9172                        info == null ? -1 : info.getReceivedTime());
9173
9174        final long ident = mInjector.binderClearCallingIdentity();
9175        try {
9176            synchronized (this) {
9177                // Broadcast to device owner first if there is one.
9178                if (mOwners.hasDeviceOwner()) {
9179                    final UserHandle deviceOwnerUser =
9180                            UserHandle.of(mOwners.getDeviceOwnerUserId());
9181                    intent.setComponent(mOwners.getDeviceOwnerComponent());
9182                    mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
9183                }
9184            }
9185            // Get running users.
9186            final int runningUserIds[];
9187            try {
9188                runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
9189            } catch (RemoteException e) {
9190                // Shouldn't happen.
9191                Log.e(LOG_TAG, "Could not retrieve the list of running users", e);
9192                return;
9193            }
9194            // Send broadcasts to corresponding profile owners if any.
9195            for (final int userId : runningUserIds) {
9196                synchronized (this) {
9197                    final ComponentName profileOwnerPackage =
9198                            mOwners.getProfileOwnerComponent(userId);
9199                    if (profileOwnerPackage != null) {
9200                        intent.setComponent(profileOwnerPackage);
9201                        mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
9202                    }
9203                }
9204            }
9205        } finally {
9206            mInjector.binderRestoreCallingIdentity(ident);
9207        }
9208    }
9209
9210    @Override
9211    public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
9212        Preconditions.checkNotNull(admin, "ComponentName is null");
9213        enforceProfileOrDeviceOwner(admin);
9214
9215        return mOwners.getSystemUpdateInfo();
9216    }
9217
9218    @Override
9219    public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy)
9220            throws RemoteException {
9221        int userId = UserHandle.getCallingUserId();
9222        synchronized (this) {
9223            // Ensure the caller is a DO/PO or a permission grant state delegate.
9224            enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9225                    DELEGATION_PERMISSION_GRANT);
9226            DevicePolicyData userPolicy = getUserData(userId);
9227            if (userPolicy.mPermissionPolicy != policy) {
9228                userPolicy.mPermissionPolicy = policy;
9229                saveSettingsLocked(userId);
9230            }
9231        }
9232    }
9233
9234    @Override
9235    public int getPermissionPolicy(ComponentName admin) throws RemoteException {
9236        int userId = UserHandle.getCallingUserId();
9237        synchronized (this) {
9238            DevicePolicyData userPolicy = getUserData(userId);
9239            return userPolicy.mPermissionPolicy;
9240        }
9241    }
9242
9243    @Override
9244    public boolean setPermissionGrantState(ComponentName admin, String callerPackage,
9245            String packageName, String permission, int grantState) throws RemoteException {
9246        UserHandle user = mInjector.binderGetCallingUserHandle();
9247        synchronized (this) {
9248            // Ensure the caller is a DO/PO or a permission grant state delegate.
9249            enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9250                    DELEGATION_PERMISSION_GRANT);
9251            long ident = mInjector.binderClearCallingIdentity();
9252            try {
9253                if (getTargetSdk(packageName, user.getIdentifier())
9254                        < android.os.Build.VERSION_CODES.M) {
9255                    return false;
9256                }
9257                final PackageManager packageManager = mInjector.getPackageManager();
9258                switch (grantState) {
9259                    case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
9260                        mInjector.getPackageManagerInternal().grantRuntimePermission(packageName,
9261                                permission, user.getIdentifier(), true /* override policy */);
9262                        packageManager.updatePermissionFlags(permission, packageName,
9263                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
9264                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
9265                    } break;
9266
9267                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
9268                        mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName,
9269                                permission, user.getIdentifier(), true /* override policy */);
9270                        packageManager.updatePermissionFlags(permission, packageName,
9271                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
9272                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
9273                    } break;
9274
9275                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
9276                        packageManager.updatePermissionFlags(permission, packageName,
9277                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
9278                    } break;
9279                }
9280                return true;
9281            } catch (SecurityException se) {
9282                return false;
9283            } finally {
9284                mInjector.binderRestoreCallingIdentity(ident);
9285            }
9286        }
9287    }
9288
9289    @Override
9290    public int getPermissionGrantState(ComponentName admin, String callerPackage,
9291            String packageName, String permission) throws RemoteException {
9292        PackageManager packageManager = mInjector.getPackageManager();
9293
9294        UserHandle user = mInjector.binderGetCallingUserHandle();
9295        enforceProfileOwnerOrSystemUser(admin);
9296        synchronized (this) {
9297            // Ensure the caller is a DO/PO or a permission grant state delegate.
9298            enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9299                    DELEGATION_PERMISSION_GRANT);
9300            long ident = mInjector.binderClearCallingIdentity();
9301            try {
9302                int granted = mIPackageManager.checkPermission(permission,
9303                        packageName, user.getIdentifier());
9304                int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
9305                if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
9306                        != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
9307                    // Not controlled by policy
9308                    return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
9309                } else {
9310                    // Policy controlled so return result based on permission grant state
9311                    return granted == PackageManager.PERMISSION_GRANTED
9312                            ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
9313                            : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
9314                }
9315            } finally {
9316                mInjector.binderRestoreCallingIdentity(ident);
9317            }
9318        }
9319    }
9320
9321    boolean isPackageInstalledForUser(String packageName, int userHandle) {
9322        try {
9323            PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
9324                    userHandle);
9325            return (pi != null) && (pi.applicationInfo.flags != 0);
9326        } catch (RemoteException re) {
9327            throw new RuntimeException("Package manager has died", re);
9328        }
9329    }
9330
9331    @Override
9332    public boolean isProvisioningAllowed(String action, String packageName) {
9333        Preconditions.checkNotNull(packageName);
9334
9335        final int callingUid = mInjector.binderGetCallingUid();
9336        final long ident = mInjector.binderClearCallingIdentity();
9337        try {
9338            final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser(
9339                    packageName, UserHandle.getUserId(callingUid));
9340            Preconditions.checkArgument(callingUid == uidForPackage,
9341                    "Caller uid doesn't match the one for the provided package.");
9342        } catch (NameNotFoundException e) {
9343            throw new IllegalArgumentException("Invalid package provided " + packageName, e);
9344        } finally {
9345            mInjector.binderRestoreCallingIdentity(ident);
9346        }
9347
9348        return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK;
9349    }
9350
9351    @Override
9352    public int checkProvisioningPreCondition(String action, String packageName) {
9353        Preconditions.checkNotNull(packageName);
9354        enforceCanManageProfileAndDeviceOwners();
9355        return checkProvisioningPreConditionSkipPermission(action, packageName);
9356    }
9357
9358    private int checkProvisioningPreConditionSkipPermission(String action, String packageName) {
9359        if (!mHasFeature) {
9360            return CODE_DEVICE_ADMIN_NOT_SUPPORTED;
9361        }
9362
9363        final int callingUserId = mInjector.userHandleGetCallingUserId();
9364        if (action != null) {
9365            switch (action) {
9366                case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
9367                    return checkManagedProfileProvisioningPreCondition(packageName, callingUserId);
9368                case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
9369                    return checkDeviceOwnerProvisioningPreCondition(callingUserId);
9370                case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER:
9371                    return checkManagedUserProvisioningPreCondition(callingUserId);
9372                case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE:
9373                    return checkManagedShareableDeviceProvisioningPreCondition(callingUserId);
9374            }
9375        }
9376        throw new IllegalArgumentException("Unknown provisioning action " + action);
9377    }
9378
9379    /**
9380     * The device owner can only be set before the setup phase of the primary user has completed,
9381     * except for adb command if no accounts or additional users are present on the device.
9382     */
9383    private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
9384            int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) {
9385        if (mOwners.hasDeviceOwner()) {
9386            return CODE_HAS_DEVICE_OWNER;
9387        }
9388        if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
9389            return CODE_USER_HAS_PROFILE_OWNER;
9390        }
9391        if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
9392            return CODE_USER_NOT_RUNNING;
9393        }
9394        if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
9395            return CODE_HAS_PAIRED;
9396        }
9397        if (isAdb) {
9398            // if shell command runs after user setup completed check device status. Otherwise, OK.
9399            if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
9400                if (!mInjector.userManagerIsSplitSystemUser()) {
9401                    if (mUserManager.getUserCount() > 1) {
9402                        return CODE_NONSYSTEM_USER_EXISTS;
9403                    }
9404                    if (hasIncompatibleAccountsOrNonAdb) {
9405                        return CODE_ACCOUNTS_NOT_EMPTY;
9406                    }
9407                } else {
9408                    // STOPSHIP Do proper check in split user mode
9409                }
9410            }
9411            return CODE_OK;
9412        } else {
9413            if (!mInjector.userManagerIsSplitSystemUser()) {
9414                // In non-split user mode, DO has to be user 0
9415                if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
9416                    return CODE_NOT_SYSTEM_USER;
9417                }
9418                // In non-split user mode, only provision DO before setup wizard completes
9419                if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
9420                    return CODE_USER_SETUP_COMPLETED;
9421                }
9422            } else {
9423                // STOPSHIP Do proper check in split user mode
9424            }
9425            return CODE_OK;
9426        }
9427    }
9428
9429    private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) {
9430        synchronized (this) {
9431            // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
9432            return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
9433                    deviceOwnerUserId, /* isAdb= */ false,
9434                    /* hasIncompatibleAccountsOrNonAdb=*/ true);
9435        }
9436    }
9437
9438    private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) {
9439        if (!hasFeatureManagedUsers()) {
9440            return CODE_MANAGED_USERS_NOT_SUPPORTED;
9441        }
9442        if (callingUserId == UserHandle.USER_SYSTEM
9443                && mInjector.userManagerIsSplitSystemUser()) {
9444            // Managed-profiles cannot be setup on the system user.
9445            return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
9446        }
9447        if (getProfileOwner(callingUserId) != null) {
9448            // Managed user cannot have a managed profile.
9449            return CODE_USER_HAS_PROFILE_OWNER;
9450        }
9451
9452        final long ident = mInjector.binderClearCallingIdentity();
9453        try {
9454            final UserHandle callingUserHandle = UserHandle.of(callingUserId);
9455            final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId);
9456            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
9457                    callingUserHandle)) {
9458                // An admin can initiate provisioning if it has set the restriction.
9459                if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
9460                        UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) {
9461                    return CODE_ADD_MANAGED_PROFILE_DISALLOWED;
9462                }
9463            }
9464            boolean canRemoveProfile = true;
9465            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
9466                    callingUserHandle)) {
9467                // We can remove a profile if the admin itself has set the restriction.
9468                if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
9469                        UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
9470                        callingUserId)) {
9471                    canRemoveProfile = false;
9472                }
9473            }
9474            if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) {
9475                return CODE_CANNOT_ADD_MANAGED_PROFILE;
9476            }
9477        } finally {
9478            mInjector.binderRestoreCallingIdentity(ident);
9479        }
9480        return CODE_OK;
9481    }
9482
9483    private ComponentName getOwnerComponent(String packageName, int userId) {
9484        if (isDeviceOwnerPackage(packageName, userId)) {
9485            return mOwners.getDeviceOwnerComponent();
9486        }
9487        if (isProfileOwnerPackage(packageName, userId)) {
9488            return mOwners.getProfileOwnerComponent(userId);
9489        }
9490        return null;
9491    }
9492
9493    private int checkManagedUserProvisioningPreCondition(int callingUserId) {
9494        if (!hasFeatureManagedUsers()) {
9495            return CODE_MANAGED_USERS_NOT_SUPPORTED;
9496        }
9497        if (!mInjector.userManagerIsSplitSystemUser()) {
9498            // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
9499            return CODE_NOT_SYSTEM_USER_SPLIT;
9500        }
9501        if (callingUserId == UserHandle.USER_SYSTEM) {
9502            // System user cannot be a managed user.
9503            return CODE_SYSTEM_USER;
9504        }
9505        if (hasUserSetupCompleted(callingUserId)) {
9506            return CODE_USER_SETUP_COMPLETED;
9507        }
9508        if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
9509            return CODE_HAS_PAIRED;
9510        }
9511        return CODE_OK;
9512    }
9513
9514    private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) {
9515        if (!mInjector.userManagerIsSplitSystemUser()) {
9516            // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
9517            return CODE_NOT_SYSTEM_USER_SPLIT;
9518        }
9519        return checkDeviceOwnerProvisioningPreCondition(callingUserId);
9520    }
9521
9522    private boolean hasFeatureManagedUsers() {
9523        try {
9524            return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
9525        } catch (RemoteException e) {
9526            return false;
9527        }
9528    }
9529
9530    @Override
9531    public String getWifiMacAddress(ComponentName admin) {
9532        // Make sure caller has DO.
9533        synchronized (this) {
9534            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9535        }
9536
9537        final long ident = mInjector.binderClearCallingIdentity();
9538        try {
9539            final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
9540            if (wifiInfo == null) {
9541                return null;
9542            }
9543            return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
9544        } finally {
9545            mInjector.binderRestoreCallingIdentity(ident);
9546        }
9547    }
9548
9549    /**
9550     * Returns the target sdk version number that the given packageName was built for
9551     * in the given user.
9552     */
9553    private int getTargetSdk(String packageName, int userId) {
9554        final ApplicationInfo ai;
9555        try {
9556            ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
9557            final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
9558            return targetSdkVersion;
9559        } catch (RemoteException e) {
9560            // Shouldn't happen
9561            return 0;
9562        }
9563    }
9564
9565    @Override
9566    public boolean isManagedProfile(ComponentName admin) {
9567        enforceProfileOrDeviceOwner(admin);
9568        return isManagedProfile(mInjector.userHandleGetCallingUserId());
9569    }
9570
9571    @Override
9572    public boolean isSystemOnlyUser(ComponentName admin) {
9573        synchronized (this) {
9574            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9575        }
9576        final int callingUserId = mInjector.userHandleGetCallingUserId();
9577        return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
9578    }
9579
9580    @Override
9581    public void reboot(ComponentName admin) {
9582        Preconditions.checkNotNull(admin);
9583        // Make sure caller has DO.
9584        synchronized (this) {
9585            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9586        }
9587        long ident = mInjector.binderClearCallingIdentity();
9588        try {
9589            // Make sure there are no ongoing calls on the device.
9590            if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
9591                throw new IllegalStateException("Cannot be called with ongoing call on the device");
9592            }
9593            mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
9594        } finally {
9595            mInjector.binderRestoreCallingIdentity(ident);
9596        }
9597    }
9598
9599    @Override
9600    public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
9601        if (!mHasFeature) {
9602            return;
9603        }
9604        Preconditions.checkNotNull(who, "ComponentName is null");
9605        final int userHandle = mInjector.userHandleGetCallingUserId();
9606        synchronized (this) {
9607            ActiveAdmin admin = getActiveAdminForUidLocked(who,
9608                    mInjector.binderGetCallingUid());
9609            if (!TextUtils.equals(admin.shortSupportMessage, message)) {
9610                admin.shortSupportMessage = message;
9611                saveSettingsLocked(userHandle);
9612            }
9613        }
9614    }
9615
9616    @Override
9617    public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
9618        if (!mHasFeature) {
9619            return null;
9620        }
9621        Preconditions.checkNotNull(who, "ComponentName is null");
9622        synchronized (this) {
9623            ActiveAdmin admin = getActiveAdminForUidLocked(who,
9624                    mInjector.binderGetCallingUid());
9625            return admin.shortSupportMessage;
9626        }
9627    }
9628
9629    @Override
9630    public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
9631        if (!mHasFeature) {
9632            return;
9633        }
9634        Preconditions.checkNotNull(who, "ComponentName is null");
9635        final int userHandle = mInjector.userHandleGetCallingUserId();
9636        synchronized (this) {
9637            ActiveAdmin admin = getActiveAdminForUidLocked(who,
9638                    mInjector.binderGetCallingUid());
9639            if (!TextUtils.equals(admin.longSupportMessage, message)) {
9640                admin.longSupportMessage = message;
9641                saveSettingsLocked(userHandle);
9642            }
9643        }
9644    }
9645
9646    @Override
9647    public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
9648        if (!mHasFeature) {
9649            return null;
9650        }
9651        Preconditions.checkNotNull(who, "ComponentName is null");
9652        synchronized (this) {
9653            ActiveAdmin admin = getActiveAdminForUidLocked(who,
9654                    mInjector.binderGetCallingUid());
9655            return admin.longSupportMessage;
9656        }
9657    }
9658
9659    @Override
9660    public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
9661        if (!mHasFeature) {
9662            return null;
9663        }
9664        Preconditions.checkNotNull(who, "ComponentName is null");
9665        if (!isCallerWithSystemUid()) {
9666            throw new SecurityException("Only the system can query support message for user");
9667        }
9668        synchronized (this) {
9669            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
9670            if (admin != null) {
9671                return admin.shortSupportMessage;
9672            }
9673        }
9674        return null;
9675    }
9676
9677    @Override
9678    public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
9679        if (!mHasFeature) {
9680            return null;
9681        }
9682        Preconditions.checkNotNull(who, "ComponentName is null");
9683        if (!isCallerWithSystemUid()) {
9684            throw new SecurityException("Only the system can query support message for user");
9685        }
9686        synchronized (this) {
9687            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
9688            if (admin != null) {
9689                return admin.longSupportMessage;
9690            }
9691        }
9692        return null;
9693    }
9694
9695    @Override
9696    public void setOrganizationColor(@NonNull ComponentName who, int color) {
9697        if (!mHasFeature) {
9698            return;
9699        }
9700        Preconditions.checkNotNull(who, "ComponentName is null");
9701        final int userHandle = mInjector.userHandleGetCallingUserId();
9702        enforceManagedProfile(userHandle, "set organization color");
9703        synchronized (this) {
9704            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9705                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9706            admin.organizationColor = color;
9707            saveSettingsLocked(userHandle);
9708        }
9709    }
9710
9711    @Override
9712    public void setOrganizationColorForUser(int color, int userId) {
9713        if (!mHasFeature) {
9714            return;
9715        }
9716        enforceFullCrossUsersPermission(userId);
9717        enforceManageUsers();
9718        enforceManagedProfile(userId, "set organization color");
9719        synchronized (this) {
9720            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9721            admin.organizationColor = color;
9722            saveSettingsLocked(userId);
9723        }
9724    }
9725
9726    @Override
9727    public int getOrganizationColor(@NonNull ComponentName who) {
9728        if (!mHasFeature) {
9729            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9730        }
9731        Preconditions.checkNotNull(who, "ComponentName is null");
9732        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
9733        synchronized (this) {
9734            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9735                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9736            return admin.organizationColor;
9737        }
9738    }
9739
9740    @Override
9741    public int getOrganizationColorForUser(int userHandle) {
9742        if (!mHasFeature) {
9743            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9744        }
9745        enforceFullCrossUsersPermission(userHandle);
9746        enforceManagedProfile(userHandle, "get organization color");
9747        synchronized (this) {
9748            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9749            return (profileOwner != null)
9750                    ? profileOwner.organizationColor
9751                    : ActiveAdmin.DEF_ORGANIZATION_COLOR;
9752        }
9753    }
9754
9755    @Override
9756    public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
9757        if (!mHasFeature) {
9758            return;
9759        }
9760        Preconditions.checkNotNull(who, "ComponentName is null");
9761        final int userHandle = mInjector.userHandleGetCallingUserId();
9762
9763        synchronized (this) {
9764            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9765                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9766            if (!TextUtils.equals(admin.organizationName, text)) {
9767                admin.organizationName = (text == null || text.length() == 0)
9768                        ? null : text.toString();
9769                saveSettingsLocked(userHandle);
9770            }
9771        }
9772    }
9773
9774    @Override
9775    public CharSequence getOrganizationName(@NonNull ComponentName who) {
9776        if (!mHasFeature) {
9777            return null;
9778        }
9779        Preconditions.checkNotNull(who, "ComponentName is null");
9780        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
9781        synchronized(this) {
9782            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9783                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9784            return admin.organizationName;
9785        }
9786    }
9787
9788    @Override
9789    public CharSequence getDeviceOwnerOrganizationName() {
9790        if (!mHasFeature) {
9791            return null;
9792        }
9793        enforceDeviceOwnerOrManageUsers();
9794        synchronized(this) {
9795            final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
9796            return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
9797        }
9798    }
9799
9800    @Override
9801    public CharSequence getOrganizationNameForUser(int userHandle) {
9802        if (!mHasFeature) {
9803            return null;
9804        }
9805        enforceFullCrossUsersPermission(userHandle);
9806        enforceManagedProfile(userHandle, "get organization name");
9807        synchronized (this) {
9808            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9809            return (profileOwner != null)
9810                    ? profileOwner.organizationName
9811                    : null;
9812        }
9813    }
9814
9815    @Override
9816    public void setAffiliationIds(ComponentName admin, List<String> ids) {
9817        if (!mHasFeature) {
9818            return;
9819        }
9820
9821        Preconditions.checkNotNull(admin);
9822        Preconditions.checkCollectionElementsNotNull(ids, "ids");
9823
9824        final Set<String> affiliationIds = new ArraySet<String>(ids);
9825        Preconditions.checkArgument(
9826                !affiliationIds.contains(""), "ids must not contain empty strings");
9827
9828        final int callingUserId = mInjector.userHandleGetCallingUserId();
9829        synchronized (this) {
9830            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9831            getUserData(callingUserId).mAffiliationIds = affiliationIds;
9832            saveSettingsLocked(callingUserId);
9833            if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
9834                // Affiliation ids specified by the device owner are additionally stored in
9835                // UserHandle.USER_SYSTEM's DevicePolicyData.
9836                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
9837                saveSettingsLocked(UserHandle.USER_SYSTEM);
9838            }
9839
9840            // Affiliation status for any user, not just the calling user, might have changed.
9841            // The device owner user will still be affiliated after changing its affiliation ids,
9842            // but as a result of that other users might become affiliated or un-affiliated.
9843            maybePauseDeviceWideLoggingLocked();
9844            maybeResumeDeviceWideLoggingLocked();
9845        }
9846    }
9847
9848    @Override
9849    public List<String> getAffiliationIds(ComponentName admin) {
9850        if (!mHasFeature) {
9851            return Collections.emptyList();
9852        }
9853
9854        Preconditions.checkNotNull(admin);
9855        synchronized (this) {
9856            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9857            return new ArrayList<String>(
9858                    getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds);
9859        }
9860    }
9861
9862    @Override
9863    public boolean isAffiliatedUser() {
9864        if (!mHasFeature) {
9865            return false;
9866        }
9867
9868        synchronized (this) {
9869            return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
9870        }
9871    }
9872
9873    private boolean isUserAffiliatedWithDeviceLocked(int userId) {
9874        if (!mOwners.hasDeviceOwner()) {
9875            return false;
9876        }
9877        if (userId == mOwners.getDeviceOwnerUserId()) {
9878            // The user that the DO is installed on is always affiliated with the device.
9879            return true;
9880        }
9881        if (userId == UserHandle.USER_SYSTEM) {
9882            // The system user is always affiliated in a DO device, even if the DO is set on a
9883            // different user. This could be the case if the DO is set in the primary user
9884            // of a split user device.
9885            return true;
9886        }
9887        final ComponentName profileOwner = getProfileOwner(userId);
9888        if (profileOwner == null) {
9889            return false;
9890        }
9891        final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
9892        final Set<String> deviceAffiliationIds =
9893                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
9894        for (String id : userAffiliationIds) {
9895            if (deviceAffiliationIds.contains(id)) {
9896                return true;
9897            }
9898        }
9899        return false;
9900    }
9901
9902    private boolean areAllUsersAffiliatedWithDeviceLocked() {
9903        final long ident = mInjector.binderClearCallingIdentity();
9904        try {
9905            final List<UserInfo> userInfos = mUserManager.getUsers();
9906            for (int i = 0; i < userInfos.size(); i++) {
9907                int userId = userInfos.get(i).id;
9908                if (!isUserAffiliatedWithDeviceLocked(userId)) {
9909                    Slog.d(LOG_TAG, "User id " + userId + " not affiliated.");
9910                    return false;
9911                }
9912            }
9913        } finally {
9914            mInjector.binderRestoreCallingIdentity(ident);
9915        }
9916
9917        return true;
9918    }
9919
9920    @Override
9921    public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
9922        if (!mHasFeature) {
9923            return;
9924        }
9925        Preconditions.checkNotNull(admin);
9926
9927        synchronized (this) {
9928            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9929            if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
9930                return;
9931            }
9932            mInjector.securityLogSetLoggingEnabledProperty(enabled);
9933            if (enabled) {
9934                mSecurityLogMonitor.start();
9935                maybePauseDeviceWideLoggingLocked();
9936            } else {
9937                mSecurityLogMonitor.stop();
9938            }
9939        }
9940    }
9941
9942    @Override
9943    public boolean isSecurityLoggingEnabled(ComponentName admin) {
9944        if (!mHasFeature) {
9945            return false;
9946        }
9947
9948        Preconditions.checkNotNull(admin);
9949        synchronized (this) {
9950            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9951            return mInjector.securityLogGetLoggingEnabledProperty();
9952        }
9953    }
9954
9955    private synchronized void recordSecurityLogRetrievalTime() {
9956        final long currentTime = System.currentTimeMillis();
9957        DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
9958        if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
9959            policyData.mLastSecurityLogRetrievalTime = currentTime;
9960            saveSettingsLocked(UserHandle.USER_SYSTEM);
9961        }
9962    }
9963
9964    @Override
9965    public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
9966        if (!mHasFeature) {
9967            return null;
9968        }
9969
9970        Preconditions.checkNotNull(admin);
9971        ensureDeviceOwnerAndAllUsersAffiliated(admin);
9972
9973        if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
9974                || !mInjector.securityLogGetLoggingEnabledProperty()) {
9975            return null;
9976        }
9977
9978        recordSecurityLogRetrievalTime();
9979
9980        ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
9981        try {
9982            SecurityLog.readPreviousEvents(output);
9983            return new ParceledListSlice<SecurityEvent>(output);
9984        } catch (IOException e) {
9985            Slog.w(LOG_TAG, "Fail to read previous events" , e);
9986            return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
9987        }
9988    }
9989
9990    @Override
9991    public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
9992        if (!mHasFeature) {
9993            return null;
9994        }
9995
9996        Preconditions.checkNotNull(admin);
9997        ensureDeviceOwnerAndAllUsersAffiliated(admin);
9998
9999        if (!mInjector.securityLogGetLoggingEnabledProperty()) {
10000            return null;
10001        }
10002
10003        recordSecurityLogRetrievalTime();
10004
10005        List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
10006        return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
10007    }
10008
10009    private void enforceCanManageDeviceAdmin() {
10010        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
10011                null);
10012    }
10013
10014    private void enforceCanManageProfileAndDeviceOwners() {
10015        mContext.enforceCallingOrSelfPermission(
10016                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
10017    }
10018
10019    private void enforceCallerSystemUserHandle() {
10020        final int callingUid = mInjector.binderGetCallingUid();
10021        final int userId = UserHandle.getUserId(callingUid);
10022        if (userId != UserHandle.USER_SYSTEM) {
10023            throw new SecurityException("Caller has to be in user 0");
10024        }
10025    }
10026
10027    @Override
10028    public boolean isUninstallInQueue(final String packageName) {
10029        enforceCanManageDeviceAdmin();
10030        final int userId = mInjector.userHandleGetCallingUserId();
10031        Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10032        synchronized (this) {
10033            return mPackagesToRemove.contains(packageUserPair);
10034        }
10035    }
10036
10037    @Override
10038    public void uninstallPackageWithActiveAdmins(final String packageName) {
10039        enforceCanManageDeviceAdmin();
10040        Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
10041
10042        final int userId = mInjector.userHandleGetCallingUserId();
10043
10044        enforceUserUnlocked(userId);
10045
10046        final ComponentName profileOwner = getProfileOwner(userId);
10047        if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
10048            throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
10049        }
10050
10051        final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
10052        if (getDeviceOwnerUserId() == userId && deviceOwner != null
10053                && packageName.equals(deviceOwner.getPackageName())) {
10054            throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
10055        }
10056
10057        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10058        synchronized (this) {
10059            mPackagesToRemove.add(packageUserPair);
10060        }
10061
10062        // All active admins on the user.
10063        final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
10064
10065        // Active admins in the target package.
10066        final List<ComponentName> packageActiveAdmins = new ArrayList<>();
10067        if (allActiveAdmins != null) {
10068            for (ComponentName activeAdmin : allActiveAdmins) {
10069                if (packageName.equals(activeAdmin.getPackageName())) {
10070                    packageActiveAdmins.add(activeAdmin);
10071                    removeActiveAdmin(activeAdmin, userId);
10072                }
10073            }
10074        }
10075        if (packageActiveAdmins.size() == 0) {
10076            startUninstallIntent(packageName, userId);
10077        } else {
10078            mHandler.postDelayed(new Runnable() {
10079                @Override
10080                public void run() {
10081                    for (ComponentName activeAdmin : packageActiveAdmins) {
10082                        removeAdminArtifacts(activeAdmin, userId);
10083                    }
10084                    startUninstallIntent(packageName, userId);
10085                }
10086            }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
10087        }
10088    }
10089
10090    @Override
10091    public boolean isDeviceProvisioned() {
10092        return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
10093    }
10094
10095    private void removePackageIfRequired(final String packageName, final int userId) {
10096        if (!packageHasActiveAdmins(packageName, userId)) {
10097            // Will not do anything if uninstall was not requested or was already started.
10098            startUninstallIntent(packageName, userId);
10099        }
10100    }
10101
10102    private void startUninstallIntent(final String packageName, final int userId) {
10103        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10104        synchronized (this) {
10105            if (!mPackagesToRemove.contains(packageUserPair)) {
10106                // Do nothing if uninstall was not requested or was already started.
10107                return;
10108            }
10109            mPackagesToRemove.remove(packageUserPair);
10110        }
10111        try {
10112            if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
10113                // Package does not exist. Nothing to do.
10114                return;
10115            }
10116        } catch (RemoteException re) {
10117            Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
10118        }
10119
10120        try { // force stop the package before uninstalling
10121            mInjector.getIActivityManager().forceStopPackage(packageName, userId);
10122        } catch (RemoteException re) {
10123            Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
10124        }
10125        final Uri packageURI = Uri.parse("package:" + packageName);
10126        final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
10127        uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
10128        mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
10129    }
10130
10131    /**
10132     * Removes the admin from the policy. Ideally called after the admin's
10133     * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
10134     *
10135     * @param adminReceiver The admin to remove
10136     * @param userHandle The user for which this admin has to be removed.
10137     */
10138    private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
10139        synchronized (this) {
10140            final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
10141            if (admin == null) {
10142                return;
10143            }
10144            final DevicePolicyData policy = getUserData(userHandle);
10145            final boolean doProxyCleanup = admin.info.usesPolicy(
10146                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
10147            policy.mAdminList.remove(admin);
10148            policy.mAdminMap.remove(adminReceiver);
10149            validatePasswordOwnerLocked(policy);
10150            if (doProxyCleanup) {
10151                resetGlobalProxyLocked(policy);
10152            }
10153            saveSettingsLocked(userHandle);
10154            updateMaximumTimeToLockLocked(userHandle);
10155            policy.mRemovingAdmins.remove(adminReceiver);
10156
10157            Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
10158        }
10159        // The removed admin might have disabled camera, so update user
10160        // restrictions.
10161        pushUserRestrictions(userHandle);
10162    }
10163
10164    @Override
10165    public void setDeviceProvisioningConfigApplied() {
10166        enforceManageUsers();
10167        synchronized (this) {
10168            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
10169            policy.mDeviceProvisioningConfigApplied = true;
10170            saveSettingsLocked(UserHandle.USER_SYSTEM);
10171        }
10172    }
10173
10174    @Override
10175    public boolean isDeviceProvisioningConfigApplied() {
10176        enforceManageUsers();
10177        synchronized (this) {
10178            final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
10179            return policy.mDeviceProvisioningConfigApplied;
10180        }
10181    }
10182
10183    /**
10184     * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
10185     *
10186     * It's added for testing only. Please use this API carefully if it's used by other system app
10187     * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
10188     * apps.
10189     */
10190    @Override
10191    public void forceUpdateUserSetupComplete() {
10192        enforceCanManageProfileAndDeviceOwners();
10193        enforceCallerSystemUserHandle();
10194        // no effect if it's called from user build
10195        if (!mInjector.isBuildDebuggable()) {
10196            return;
10197        }
10198        final int userId = UserHandle.USER_SYSTEM;
10199        boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
10200                Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
10201        DevicePolicyData policy = getUserData(userId);
10202        policy.mUserSetupComplete = isUserCompleted;
10203        synchronized (this) {
10204            saveSettingsLocked(userId);
10205        }
10206    }
10207
10208    // TODO(b/22388012): When backup is available for secondary users and profiles, consider
10209    // whether there are any privacy/security implications of enabling the backup service here
10210    // if there are other users or profiles unmanaged or managed by a different entity (i.e. not
10211    // affiliated).
10212    @Override
10213    public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
10214        if (!mHasFeature) {
10215            return;
10216        }
10217        Preconditions.checkNotNull(admin);
10218        synchronized (this) {
10219            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10220        }
10221
10222        final long ident = mInjector.binderClearCallingIdentity();
10223        try {
10224            IBackupManager ibm = mInjector.getIBackupManager();
10225            if (ibm != null) {
10226                ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
10227            }
10228        } catch (RemoteException e) {
10229            throw new IllegalStateException(
10230                "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
10231        } finally {
10232            mInjector.binderRestoreCallingIdentity(ident);
10233        }
10234    }
10235
10236    @Override
10237    public boolean isBackupServiceEnabled(ComponentName admin) {
10238        Preconditions.checkNotNull(admin);
10239        if (!mHasFeature) {
10240            return true;
10241        }
10242        synchronized (this) {
10243            try {
10244                getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10245                IBackupManager ibm = mInjector.getIBackupManager();
10246                return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
10247            } catch (RemoteException e) {
10248                throw new IllegalStateException("Failed requesting backup service state.", e);
10249            }
10250        }
10251    }
10252
10253    @Override
10254    public boolean bindDeviceAdminServiceAsUser(
10255            @NonNull ComponentName admin, @NonNull IApplicationThread caller,
10256            @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
10257            @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
10258        if (!mHasFeature) {
10259            return false;
10260        }
10261        Preconditions.checkNotNull(admin);
10262        Preconditions.checkNotNull(caller);
10263        Preconditions.checkNotNull(serviceIntent);
10264        Preconditions.checkArgument(
10265                serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
10266                "Service intent must be explicit (with a package name or component): "
10267                        + serviceIntent);
10268        Preconditions.checkNotNull(connection);
10269        Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
10270                "target user id must be different from the calling user id");
10271
10272        if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
10273            throw new SecurityException("Not allowed to bind to target user id");
10274        }
10275
10276        final String targetPackage;
10277        synchronized (this) {
10278            targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
10279        }
10280
10281        final long callingIdentity = mInjector.binderClearCallingIdentity();
10282        try {
10283            // Validate and sanitize the incoming service intent.
10284            final Intent sanitizedIntent =
10285                    createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
10286            if (sanitizedIntent == null) {
10287                // Fail, cannot lookup the target service.
10288                return false;
10289            }
10290            // Ask ActivityManager to bind it. Notice that we are binding the service with the
10291            // caller app instead of DevicePolicyManagerService.
10292            return mInjector.getIActivityManager().bindService(
10293                    caller, activtiyToken, serviceIntent,
10294                    serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
10295                    connection, flags, mContext.getOpPackageName(),
10296                    targetUserId) != 0;
10297        } catch (RemoteException ex) {
10298            // Same process, should not happen.
10299        } finally {
10300            mInjector.binderRestoreCallingIdentity(callingIdentity);
10301        }
10302
10303        // Failed to bind.
10304        return false;
10305    }
10306
10307    @Override
10308    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
10309        if (!mHasFeature) {
10310            return Collections.emptyList();
10311        }
10312        Preconditions.checkNotNull(admin);
10313        ArrayList<UserHandle> targetUsers = new ArrayList<>();
10314
10315        synchronized (this) {
10316            ActiveAdmin callingOwner = getActiveAdminForCallerLocked(
10317                    admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10318
10319            final int callingUserId = mInjector.userHandleGetCallingUserId();
10320            final boolean isCallerDeviceOwner = isDeviceOwner(callingOwner);
10321            final boolean isCallerManagedProfile = isManagedProfile(callingUserId);
10322            if ((!isCallerDeviceOwner && !isCallerManagedProfile)
10323                    || !isUserAffiliatedWithDeviceLocked(callingUserId)) {
10324                return targetUsers;
10325            }
10326
10327            final long callingIdentity = mInjector.binderClearCallingIdentity();
10328            try {
10329                String callingOwnerPackage = callingOwner.info.getComponent().getPackageName();
10330                for (int userId : mUserManager.getProfileIdsWithDisabled(callingUserId)) {
10331                    if (userId == callingUserId) {
10332                        continue;
10333                    }
10334
10335                    // We only allow the device owner and a managed profile owner to bind to each
10336                    // other.
10337                    if ((isCallerManagedProfile && userId == mOwners.getDeviceOwnerUserId())
10338                            || (isCallerDeviceOwner && isManagedProfile(userId))) {
10339                        String targetOwnerPackage = getOwnerPackageNameForUserLocked(userId);
10340
10341                        // Both must be the same package and be affiliated in order to bind.
10342                        if (callingOwnerPackage.equals(targetOwnerPackage)
10343                               && isUserAffiliatedWithDeviceLocked(userId)) {
10344                            targetUsers.add(UserHandle.of(userId));
10345                        }
10346                    }
10347                }
10348            } finally {
10349                mInjector.binderRestoreCallingIdentity(callingIdentity);
10350            }
10351        }
10352
10353        return targetUsers;
10354    }
10355
10356    /**
10357     * Return true if a given user has any accounts that'll prevent installing a device or profile
10358     * owner {@code owner}.
10359     * - If the user has no accounts, then return false.
10360     * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
10361     * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
10362     *   ..._DISALLOWED, return true.
10363     * - Otherwise return false.
10364     *
10365     * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
10366     * when the caller is not ADB.
10367     *
10368     * DO NOT CALL IT WITH THE DPMS LOCK HELD.
10369     */
10370    private boolean hasIncompatibleAccountsOrNonAdbNoLock(
10371            int userId, @Nullable ComponentName owner) {
10372        if (!isAdb()) {
10373            return true;
10374        }
10375        wtfIfInLock();
10376
10377        final long token = mInjector.binderClearCallingIdentity();
10378        try {
10379            final AccountManager am = AccountManager.get(mContext);
10380            final Account accounts[] = am.getAccountsAsUser(userId);
10381            if (accounts.length == 0) {
10382                return false;
10383            }
10384            synchronized (this) {
10385                if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
10386                    Log.w(LOG_TAG,
10387                            "Non test-only owner can't be installed with existing accounts.");
10388                    return true;
10389                }
10390            }
10391
10392            final String[] feature_allow =
10393                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
10394            final String[] feature_disallow =
10395                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
10396
10397            boolean compatible = true;
10398            for (Account account : accounts) {
10399                if (hasAccountFeatures(am, account, feature_disallow)) {
10400                    Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
10401                    compatible = false;
10402                    break;
10403                }
10404                if (!hasAccountFeatures(am, account, feature_allow)) {
10405                    Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
10406                    compatible = false;
10407                    break;
10408                }
10409            }
10410            if (compatible) {
10411                Log.w(LOG_TAG, "All accounts are compatible");
10412            } else {
10413                Log.e(LOG_TAG, "Found incompatible accounts");
10414            }
10415            return !compatible;
10416        } finally {
10417            mInjector.binderRestoreCallingIdentity(token);
10418        }
10419    }
10420
10421    private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
10422        try {
10423            return am.hasFeatures(account, features, null, null).getResult();
10424        } catch (Exception e) {
10425            Log.w(LOG_TAG, "Failed to get account feature", e);
10426            return false;
10427        }
10428    }
10429
10430    private boolean isAdb() {
10431        final int callingUid = mInjector.binderGetCallingUid();
10432        return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
10433    }
10434
10435    @Override
10436    public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
10437        if (!mHasFeature) {
10438            return;
10439        }
10440        Preconditions.checkNotNull(admin);
10441        getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10442
10443        if (enabled == isNetworkLoggingEnabledInternalLocked()) {
10444            // already in the requested state
10445            return;
10446        }
10447        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
10448        deviceOwner.isNetworkLoggingEnabled = enabled;
10449        if (!enabled) {
10450            deviceOwner.numNetworkLoggingNotifications = 0;
10451            deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
10452        }
10453        saveSettingsLocked(mInjector.userHandleGetCallingUserId());
10454
10455        setNetworkLoggingActiveInternal(enabled);
10456    }
10457
10458    private synchronized void setNetworkLoggingActiveInternal(boolean active) {
10459        final long callingIdentity = mInjector.binderClearCallingIdentity();
10460        try {
10461            if (active) {
10462                mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
10463                if (!mNetworkLogger.startNetworkLogging()) {
10464                    mNetworkLogger = null;
10465                    Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
10466                            + " service not being available yet.");
10467                }
10468                maybePauseDeviceWideLoggingLocked();
10469                sendNetworkLoggingNotificationLocked();
10470            } else {
10471                if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
10472                    Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
10473                            + " service not being available yet.");
10474                }
10475                mNetworkLogger = null;
10476                mInjector.getNotificationManager().cancel(NETWORK_LOGGING_NOTIFICATION_ID);
10477            }
10478        } finally {
10479            mInjector.binderRestoreCallingIdentity(callingIdentity);
10480        }
10481    }
10482
10483    /** Pauses security and network logging if there are unaffiliated users on the device */
10484    private void maybePauseDeviceWideLoggingLocked() {
10485        if (!areAllUsersAffiliatedWithDeviceLocked()) {
10486            Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be "
10487                    + "paused if enabled.");
10488            mSecurityLogMonitor.pause();
10489            if (mNetworkLogger != null) {
10490                mNetworkLogger.pause();
10491            }
10492        }
10493    }
10494
10495    /** Resumes security and network logging (if they are enabled) if all users are affiliated */
10496    private void maybeResumeDeviceWideLoggingLocked() {
10497        if (areAllUsersAffiliatedWithDeviceLocked()) {
10498            final long ident = mInjector.binderClearCallingIdentity();
10499            try {
10500                mSecurityLogMonitor.resume();
10501                if (mNetworkLogger != null) {
10502                    mNetworkLogger.resume();
10503                }
10504            } finally {
10505                mInjector.binderRestoreCallingIdentity(ident);
10506            }
10507        }
10508    }
10509
10510    /** Deletes any security and network logs that might have been collected so far */
10511    private void discardDeviceWideLogsLocked() {
10512        mSecurityLogMonitor.discardLogs();
10513        if (mNetworkLogger != null) {
10514            mNetworkLogger.discardLogs();
10515        }
10516        // TODO: We should discard pre-boot security logs here too, as otherwise those
10517        // logs (which might contain data from the user just removed) will be
10518        // available after next boot.
10519    }
10520
10521    @Override
10522    public boolean isNetworkLoggingEnabled(ComponentName admin) {
10523        if (!mHasFeature) {
10524            return false;
10525        }
10526        synchronized (this) {
10527            enforceDeviceOwnerOrManageUsers();
10528            return isNetworkLoggingEnabledInternalLocked();
10529        }
10530    }
10531
10532    private boolean isNetworkLoggingEnabledInternalLocked() {
10533        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
10534        return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
10535    }
10536
10537    /*
10538     * A maximum of 1200 events are returned, and the total marshalled size is in the order of
10539     * 100kB, so returning a List instead of ParceledListSlice is acceptable.
10540     * Ideally this would be done with ParceledList, however it only supports homogeneous types.
10541     *
10542     * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
10543     */
10544    @Override
10545    public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) {
10546        if (!mHasFeature) {
10547            return null;
10548        }
10549        Preconditions.checkNotNull(admin);
10550        ensureDeviceOwnerAndAllUsersAffiliated(admin);
10551
10552        synchronized (this) {
10553            if (mNetworkLogger == null
10554                    || !isNetworkLoggingEnabledInternalLocked()) {
10555                return null;
10556            }
10557
10558            final long currentTime = System.currentTimeMillis();
10559            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
10560            if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
10561                policyData.mLastNetworkLogsRetrievalTime = currentTime;
10562                saveSettingsLocked(UserHandle.USER_SYSTEM);
10563            }
10564            return mNetworkLogger.retrieveLogs(batchToken);
10565        }
10566    }
10567
10568    private void sendNetworkLoggingNotificationLocked() {
10569        final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
10570        if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
10571            return;
10572        }
10573        if (deviceOwner.numNetworkLoggingNotifications >=
10574                ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
10575            return;
10576        }
10577        final long now = System.currentTimeMillis();
10578        if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
10579            return;
10580        }
10581        deviceOwner.numNetworkLoggingNotifications++;
10582        if (deviceOwner.numNetworkLoggingNotifications
10583                >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
10584            deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
10585        } else {
10586            deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
10587        }
10588        final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
10589        intent.setPackage("com.android.systemui");
10590        final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
10591                UserHandle.CURRENT);
10592        Notification notification = new Notification.Builder(mContext)
10593                .setSmallIcon(R.drawable.ic_qs_network_logging)
10594                .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
10595                .setContentText(mContext.getString(R.string.network_logging_notification_text))
10596                .setTicker(mContext.getString(R.string.network_logging_notification_title))
10597                .setShowWhen(true)
10598                .setContentIntent(pendingIntent)
10599                .build();
10600        mInjector.getNotificationManager().notify(NETWORK_LOGGING_NOTIFICATION_ID, notification);
10601        saveSettingsLocked(mOwners.getDeviceOwnerUserId());
10602    }
10603
10604    /**
10605     * Return the package name of owner in a given user.
10606     */
10607    private String getOwnerPackageNameForUserLocked(int userId) {
10608        return mOwners.getDeviceOwnerUserId() == userId
10609                ? mOwners.getDeviceOwnerPackageName()
10610                : mOwners.getProfileOwnerPackage(userId);
10611    }
10612
10613    /**
10614     * @param rawIntent Original service intent specified by caller. It must be explicit.
10615     * @param expectedPackageName The expected package name of the resolved service.
10616     * @return Intent that have component explicitly set. {@code null} if no service is resolved
10617     *     with the given intent.
10618     * @throws SecurityException if the intent is resolved to an invalid service.
10619     */
10620    private Intent createCrossUserServiceIntent(
10621            @NonNull Intent rawIntent, @NonNull String expectedPackageName,
10622            @UserIdInt int targetUserId) throws RemoteException, SecurityException {
10623        ResolveInfo info = mIPackageManager.resolveService(
10624                rawIntent,
10625                rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
10626                0,  // flags
10627                targetUserId);
10628        if (info == null || info.serviceInfo == null) {
10629            Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent
10630                    + " or user " + targetUserId + " is not running");
10631            return null;
10632        }
10633        if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
10634            throw new SecurityException("Only allow to bind service in " + expectedPackageName);
10635        }
10636        if (info.serviceInfo.exported) {
10637            throw new SecurityException("The service must be unexported");
10638        }
10639        // It is the system server to bind the service, it would be extremely dangerous if it
10640        // can be exploited to bind any service. Set the component explicitly to make sure we
10641        // do not bind anything accidentally.
10642        rawIntent.setComponent(info.serviceInfo.getComponentName());
10643        return rawIntent;
10644    }
10645
10646    @Override
10647    public long getLastSecurityLogRetrievalTime() {
10648        enforceDeviceOwnerOrManageUsers();
10649        return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
10650     }
10651
10652    @Override
10653    public long getLastBugReportRequestTime() {
10654        enforceDeviceOwnerOrManageUsers();
10655        return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
10656     }
10657
10658    @Override
10659    public long getLastNetworkLogRetrievalTime() {
10660        enforceDeviceOwnerOrManageUsers();
10661        return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime;
10662    }
10663}
10664