OSDN Git Service

60a207f946a6f55903f11cf3ca80c245bea57fbf
[android-x86/frameworks-base.git] / services / devicepolicy / java / com / android / server / devicepolicy / DevicePolicyManagerService.java
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.server.devicepolicy;
18
19 import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
20 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
21 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
22 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
23 import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
24 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
25 import static org.xmlpull.v1.XmlPullParser.END_TAG;
26 import static org.xmlpull.v1.XmlPullParser.TEXT;
27
28 import android.Manifest.permission;
29 import android.accessibilityservice.AccessibilityServiceInfo;
30 import android.accounts.AccountManager;
31 import android.app.Activity;
32 import android.app.ActivityManagerNative;
33 import android.app.AlarmManager;
34 import android.app.AppGlobals;
35 import android.app.IActivityManager;
36 import android.app.Notification;
37 import android.app.NotificationManager;
38 import android.app.PendingIntent;
39 import android.app.StatusBarManager;
40 import android.app.admin.DeviceAdminInfo;
41 import android.app.admin.DeviceAdminReceiver;
42 import android.app.admin.DevicePolicyManager;
43 import android.app.admin.DevicePolicyManagerInternal;
44 import android.app.admin.IDevicePolicyManager;
45 import android.app.admin.SystemUpdatePolicy;
46 import android.app.backup.IBackupManager;
47 import android.content.BroadcastReceiver;
48 import android.content.ComponentName;
49 import android.content.ContentResolver;
50 import android.content.Context;
51 import android.content.Intent;
52 import android.content.IntentFilter;
53 import android.content.pm.ActivityInfo;
54 import android.content.pm.ApplicationInfo;
55 import android.content.pm.IPackageManager;
56 import android.content.pm.PackageManager;
57 import android.content.pm.PackageManager.NameNotFoundException;
58 import android.content.pm.PermissionInfo;
59 import android.content.pm.ResolveInfo;
60 import android.content.pm.ServiceInfo;
61 import android.content.pm.UserInfo;
62 import android.database.ContentObserver;
63 import android.graphics.Bitmap;
64 import android.media.AudioManager;
65 import android.media.IAudioService;
66 import android.net.ConnectivityManager;
67 import android.net.ProxyInfo;
68 import android.net.Uri;
69 import android.os.AsyncTask;
70 import android.os.Binder;
71 import android.os.Bundle;
72 import android.os.Environment;
73 import android.os.FileUtils;
74 import android.os.Handler;
75 import android.os.IBinder;
76 import android.os.PersistableBundle;
77 import android.os.PowerManager;
78 import android.os.PowerManagerInternal;
79 import android.os.Process;
80 import android.os.RecoverySystem;
81 import android.os.RemoteCallback;
82 import android.os.RemoteException;
83 import android.os.ServiceManager;
84 import android.os.SystemClock;
85 import android.os.SystemProperties;
86 import android.os.UserHandle;
87 import android.os.UserManager;
88 import android.os.storage.StorageManager;
89 import android.provider.ContactsContract.QuickContact;
90 import android.provider.ContactsInternal;
91 import android.provider.Settings;
92 import android.security.Credentials;
93 import android.security.IKeyChainAliasCallback;
94 import android.security.IKeyChainService;
95 import android.security.KeyChain;
96 import android.security.KeyChain.KeyChainConnection;
97 import android.service.persistentdata.PersistentDataBlockManager;
98 import android.text.TextUtils;
99 import android.util.EventLog;
100 import android.util.Log;
101 import android.util.PrintWriterPrinter;
102 import android.util.Printer;
103 import android.util.Slog;
104 import android.util.SparseArray;
105 import android.util.Xml;
106 import android.view.IWindowManager;
107 import android.view.accessibility.AccessibilityManager;
108 import android.view.accessibility.IAccessibilityManager;
109 import android.view.inputmethod.InputMethodInfo;
110 import android.view.inputmethod.InputMethodManager;
111
112 import com.android.internal.R;
113 import com.android.internal.statusbar.IStatusBarService;
114 import com.android.internal.util.FastXmlSerializer;
115 import com.android.internal.util.JournaledFile;
116 import com.android.internal.util.Preconditions;
117 import com.android.internal.util.XmlUtils;
118 import com.android.internal.widget.LockPatternUtils;
119 import com.android.server.LocalServices;
120 import com.android.server.SystemService;
121 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
122
123 import org.xmlpull.v1.XmlPullParser;
124 import org.xmlpull.v1.XmlPullParserException;
125 import org.xmlpull.v1.XmlSerializer;
126
127 import java.io.ByteArrayInputStream;
128 import java.io.File;
129 import java.io.FileDescriptor;
130 import java.io.FileInputStream;
131 import java.io.FileNotFoundException;
132 import java.io.FileOutputStream;
133 import java.io.IOException;
134 import java.io.PrintWriter;
135 import java.nio.charset.StandardCharsets;
136 import java.security.cert.CertificateException;
137 import java.security.cert.CertificateFactory;
138 import java.security.cert.X509Certificate;
139 import java.text.DateFormat;
140 import java.util.ArrayList;
141 import java.util.Arrays;
142 import java.util.Collections;
143 import java.util.Date;
144 import java.util.HashMap;
145 import java.util.HashSet;
146 import java.util.List;
147 import java.util.Map.Entry;
148 import java.util.Set;
149
150 /**
151  * Implementation of the device policy APIs.
152  */
153 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
154
155     private static final String LOG_TAG = "DevicePolicyManagerService";
156
157     private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
158
159     private static final String DEVICE_POLICIES_XML = "device_policies.xml";
160
161     private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
162
163     private static final String TAG_STATUS_BAR = "statusbar";
164
165     private static final String ATTR_DISABLED = "disabled";
166
167     private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
168             "do-not-ask-credentials-on-boot";
169
170     private static final int REQUEST_EXPIRE_PASSWORD = 5571;
171
172     private static final long MS_PER_DAY = 86400 * 1000;
173
174     private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
175
176     protected static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
177             = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
178
179     private static final int MONITORING_CERT_NOTIFICATION_ID = R.string.ssl_ca_cert_warning;
180     private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
181
182     private static final boolean DBG = false;
183
184     private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
185     private static final String ATTR_SETUP_COMPLETE = "setup-complete";
186     private static final String ATTR_PERMISSION_POLICY = "permission-policy";
187
188     private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
189
190     private static final int STATUS_BAR_DISABLE_MASK =
191             StatusBarManager.DISABLE_EXPAND |
192             StatusBarManager.DISABLE_NOTIFICATION_ICONS |
193             StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
194             StatusBarManager.DISABLE_SEARCH;
195
196     private static final int STATUS_BAR_DISABLE2_MASK =
197             StatusBarManager.DISABLE2_QUICK_SETTINGS;
198
199     private static final Set<String> DEVICE_OWNER_USER_RESTRICTIONS;
200     static {
201         DEVICE_OWNER_USER_RESTRICTIONS = new HashSet();
202         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_USB_FILE_TRANSFER);
203         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_TETHERING);
204         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_NETWORK_RESET);
205         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_FACTORY_RESET);
206         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADD_USER);
207         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
208         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
209         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
210         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_UNMUTE_MICROPHONE);
211         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADJUST_VOLUME);
212         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SMS);
213         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_FUN);
214         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SAFE_BOOT);
215         DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CREATE_WINDOWS);
216     }
217
218     // The following user restrictions cannot be changed by any active admin, including device
219     // owner and profile owner.
220     private static final Set<String> IMMUTABLE_USER_RESTRICTIONS;
221     static {
222         IMMUTABLE_USER_RESTRICTIONS = new HashSet();
223         IMMUTABLE_USER_RESTRICTIONS.add(UserManager.DISALLOW_WALLPAPER);
224     }
225
226     private static final Set<String> SECURE_SETTINGS_WHITELIST;
227     private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
228     private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
229     private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
230     static {
231         SECURE_SETTINGS_WHITELIST = new HashSet();
232         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
233         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
234         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
235
236         SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new HashSet();
237         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
238         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
239
240         GLOBAL_SETTINGS_WHITELIST = new HashSet();
241         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
242         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
243         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
244         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
245         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
246         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
247         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
248         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
249
250         GLOBAL_SETTINGS_DEPRECATED = new HashSet();
251         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
252         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
253         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
254         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
255         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
256     }
257
258     // Keyguard features that when set of a profile will affect the profiles
259     // parent user.
260     private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
261             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
262             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
263
264     // Keyguard features that are allowed to be set on a managed profile
265     private static final int PROFILE_KEYGUARD_FEATURES =
266             PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
267             | DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
268
269     final Context mContext;
270     final UserManager mUserManager;
271     final PowerManager.WakeLock mWakeLock;
272
273     final LocalService mLocalService;
274
275     final PowerManager mPowerManager;
276     final PowerManagerInternal mPowerManagerInternal;
277
278     IWindowManager mIWindowManager;
279     NotificationManager mNotificationManager;
280
281     // Stores and loads state on device and profile owners.
282     private DeviceOwner mDeviceOwner;
283
284     private final Binder mToken = new Binder();
285
286     /**
287      * Whether or not device admin feature is supported. If it isn't return defaults for all
288      * public methods.
289      */
290     private boolean mHasFeature;
291
292     public static final class Lifecycle extends SystemService {
293         private DevicePolicyManagerService mService;
294
295         public Lifecycle(Context context) {
296             super(context);
297             mService = new DevicePolicyManagerService(context);
298         }
299
300         @Override
301         public void onStart() {
302             publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
303         }
304
305         @Override
306         public void onBootPhase(int phase) {
307             if (phase == PHASE_LOCK_SETTINGS_READY) {
308                 mService.systemReady();
309             }
310         }
311     }
312
313     public static class DevicePolicyData {
314         int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
315         int mActivePasswordLength = 0;
316         int mActivePasswordUpperCase = 0;
317         int mActivePasswordLowerCase = 0;
318         int mActivePasswordLetters = 0;
319         int mActivePasswordNumeric = 0;
320         int mActivePasswordSymbols = 0;
321         int mActivePasswordNonLetter = 0;
322         int mFailedPasswordAttempts = 0;
323
324         int mUserHandle;
325         int mPasswordOwner = -1;
326         long mLastMaximumTimeToLock = -1;
327         boolean mUserSetupComplete = false;
328         int mPermissionPolicy;
329
330         final HashMap<ComponentName, ActiveAdmin> mAdminMap = new HashMap<>();
331         final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
332         final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
333
334         // This is the list of component allowed to start lock task mode.
335         List<String> mLockTaskPackages = new ArrayList<>();
336
337         boolean mStatusBarDisabled = false;
338
339         ComponentName mRestrictionsProvider;
340
341         String mDelegatedCertInstallerPackage;
342
343         boolean doNotAskCredentialsOnBoot = false;
344
345         public DevicePolicyData(int userHandle) {
346             mUserHandle = userHandle;
347         }
348     }
349
350     final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
351
352     Handler mHandler = new Handler();
353
354     BroadcastReceiver mReceiver = new BroadcastReceiver() {
355         @Override
356         public void onReceive(Context context, Intent intent) {
357             final String action = intent.getAction();
358             final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
359                     getSendingUserId());
360             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
361                     || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
362                 if (DBG) Slog.v(LOG_TAG, "Sending password expiration notifications for action "
363                         + action + " for user " + userHandle);
364                 mHandler.post(new Runnable() {
365                     @Override
366                     public void run() {
367                         handlePasswordExpirationNotification(userHandle);
368                     }
369                 });
370             }
371             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
372                     || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
373                 new MonitoringCertNotificationTask().execute(intent);
374             }
375             if (Intent.ACTION_USER_REMOVED.equals(action)) {
376                 removeUserData(userHandle);
377             } else if (Intent.ACTION_USER_STARTED.equals(action)
378                     || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
379
380                 if (Intent.ACTION_USER_STARTED.equals(action)) {
381                     // Reset the policy data
382                     synchronized (DevicePolicyManagerService.this) {
383                         mUserData.remove(userHandle);
384                     }
385                 }
386                 handlePackagesChanged(null /* check all admins */, userHandle);
387             } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
388                     || (Intent.ACTION_PACKAGE_ADDED.equals(action)
389                             && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
390                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
391             } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
392                     && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
393                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
394             } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
395                 clearWipeProfileNotification();
396             }
397         }
398     };
399
400     static class ActiveAdmin {
401         private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
402         private static final String TAG_DISABLE_CAMERA = "disable-camera";
403         private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
404         private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
405                 = "disable-bt-contacts-sharing";
406         private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
407         private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
408         private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
409         private static final String TAG_ACCOUNT_TYPE = "account-type";
410         private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
411                 = "permitted-accessiblity-services";
412         private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
413         private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
414         private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
415         private static final String TAG_TRUST_AGENT_COMPONENT = "component";
416         private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
417         private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
418         private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
419         private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
420         private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
421         private static final String TAG_PERMITTED_IMES = "permitted-imes";
422         private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
423         private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
424         private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
425         private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
426         private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
427         private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
428         private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
429         private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
430         private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
431         private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
432         private static final String ATTR_VALUE = "value";
433         private static final String TAG_PASSWORD_QUALITY = "password-quality";
434         private static final String TAG_POLICIES = "policies";
435         private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
436                 "cross-profile-widget-providers";
437         private static final String TAG_PROVIDER = "provider";
438         private static final String TAG_PACKAGE_LIST_ITEM  = "item";
439
440         final DeviceAdminInfo info;
441
442         int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
443
444         static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
445         int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
446
447         static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
448         int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
449
450         static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
451         int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
452
453         static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
454         int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
455
456         static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
457         int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
458
459         static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
460         int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
461
462         static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
463         int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
464
465         static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
466         int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
467
468         static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
469         long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
470
471         static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
472         int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
473
474         static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
475         long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
476
477         static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
478         long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
479
480         static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
481
482         int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
483
484         boolean encryptionRequested = false;
485         boolean disableCamera = false;
486         boolean disableCallerId = false;
487         boolean disableBluetoothContactSharing = true;
488         boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
489         boolean requireAutoTime = false; // Can only be set by a device owner.
490
491         static class TrustAgentInfo {
492             public PersistableBundle options;
493             TrustAgentInfo(PersistableBundle bundle) {
494                 options = bundle;
495             }
496         }
497
498         Set<String> accountTypesWithManagementDisabled = new HashSet<String>();
499
500         // The list of permitted accessibility services package namesas set by a profile
501         // or device owner. Null means all accessibility services are allowed, empty means
502         // none except system services are allowed.
503         List<String> permittedAccessiblityServices;
504
505         // The list of permitted input methods package names as set by a profile or device owner.
506         // Null means all input methods are allowed, empty means none except system imes are
507         // allowed.
508         List<String> permittedInputMethods;
509
510         // TODO: review implementation decisions with frameworks team
511         boolean specifiesGlobalProxy = false;
512         String globalProxySpec = null;
513         String globalProxyExclusionList = null;
514
515         HashMap<String, TrustAgentInfo> trustAgentInfos = new HashMap<String, TrustAgentInfo>();
516
517         List<String> crossProfileWidgetProviders;
518
519         ActiveAdmin(DeviceAdminInfo _info) {
520             info = _info;
521         }
522
523         int getUid() { return info.getActivityInfo().applicationInfo.uid; }
524
525         public UserHandle getUserHandle() {
526             return new UserHandle(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
527         }
528
529         void writeToXml(XmlSerializer out)
530                 throws IllegalArgumentException, IllegalStateException, IOException {
531             out.startTag(null, TAG_POLICIES);
532             info.writePoliciesToXml(out);
533             out.endTag(null, TAG_POLICIES);
534             if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
535                 out.startTag(null, TAG_PASSWORD_QUALITY);
536                 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
537                 out.endTag(null, TAG_PASSWORD_QUALITY);
538                 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
539                     out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
540                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
541                     out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
542                 }
543                 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
544                     out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
545                     out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
546                     out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
547                 }
548                 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
549                     out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
550                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
551                     out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
552                 }
553                 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
554                     out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
555                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
556                     out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
557                 }
558                 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
559                     out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
560                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
561                     out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
562                 }
563                 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
564                     out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
565                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
566                     out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
567                 }
568                 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
569                     out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
570                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
571                     out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
572                 }
573                 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
574                     out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
575                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
576                     out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
577                 }
578             }
579             if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
580                 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
581                 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
582                 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
583             }
584             if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
585                 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
586                 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
587                 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
588             }
589             if (specifiesGlobalProxy) {
590                 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
591                 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
592                 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
593                 if (globalProxySpec != null) {
594                     out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
595                     out.attribute(null, ATTR_VALUE, globalProxySpec);
596                     out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
597                 }
598                 if (globalProxyExclusionList != null) {
599                     out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
600                     out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
601                     out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
602                 }
603             }
604             if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
605                 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
606                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
607                 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
608             }
609             if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
610                 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
611                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
612                 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
613             }
614             if (encryptionRequested) {
615                 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
616                 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
617                 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
618             }
619             if (disableCamera) {
620                 out.startTag(null, TAG_DISABLE_CAMERA);
621                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
622                 out.endTag(null, TAG_DISABLE_CAMERA);
623             }
624             if (disableCallerId) {
625                 out.startTag(null, TAG_DISABLE_CALLER_ID);
626                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
627                 out.endTag(null, TAG_DISABLE_CALLER_ID);
628             }
629             if (disableBluetoothContactSharing) {
630                 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
631                 out.attribute(null, ATTR_VALUE,
632                         Boolean.toString(disableBluetoothContactSharing));
633                 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
634             }
635             if (disableScreenCapture) {
636                 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
637                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
638                 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
639             }
640             if (requireAutoTime) {
641                 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
642                 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
643                 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
644             }
645             if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
646                 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
647                 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
648                 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
649             }
650             if (!accountTypesWithManagementDisabled.isEmpty()) {
651                 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
652                 for (String ac : accountTypesWithManagementDisabled) {
653                     out.startTag(null, TAG_ACCOUNT_TYPE);
654                     out.attribute(null, ATTR_VALUE, ac);
655                     out.endTag(null, TAG_ACCOUNT_TYPE);
656                 }
657                 out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
658             }
659             if (!trustAgentInfos.isEmpty()) {
660                 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
661                 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
662                 for (Entry<String, TrustAgentInfo> entry : set) {
663                     TrustAgentInfo trustAgentInfo = entry.getValue();
664                     out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
665                     out.attribute(null, ATTR_VALUE, entry.getKey());
666                     if (trustAgentInfo.options != null) {
667                         out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
668                         try {
669                             trustAgentInfo.options.saveToXml(out);
670                         } catch (XmlPullParserException e) {
671                             Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
672                         }
673                         out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
674                     }
675                     out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
676                 }
677                 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
678             }
679             if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
680                 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
681                 final int providerCount = crossProfileWidgetProviders.size();
682                 for (int i = 0; i < providerCount; i++) {
683                     String provider = crossProfileWidgetProviders.get(i);
684                     out.startTag(null, TAG_PROVIDER);
685                     out.attribute(null, ATTR_VALUE, provider);
686                     out.endTag(null, TAG_PROVIDER);
687                 }
688                 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
689             }
690             writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
691                     permittedAccessiblityServices);
692             writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
693         }
694
695         void writePackageListToXml(XmlSerializer out, String outerTag,
696                 List<String> packageList)
697                 throws IllegalArgumentException, IllegalStateException, IOException {
698             if (packageList == null) {
699                 return;
700             }
701
702             out.startTag(null, outerTag);
703             for (String packageName : packageList) {
704                 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
705                 out.attribute(null, ATTR_VALUE, packageName);
706                 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
707             }
708             out.endTag(null, outerTag);
709         }
710
711         void readFromXml(XmlPullParser parser)
712                 throws XmlPullParserException, IOException {
713             int outerDepth = parser.getDepth();
714             int type;
715             while ((type=parser.next()) != END_DOCUMENT
716                    && (type != END_TAG || parser.getDepth() > outerDepth)) {
717                 if (type == END_TAG || type == TEXT) {
718                     continue;
719                 }
720                 String tag = parser.getName();
721                 if (TAG_POLICIES.equals(tag)) {
722                     info.readPoliciesFromXml(parser);
723                 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
724                     passwordQuality = Integer.parseInt(
725                             parser.getAttributeValue(null, ATTR_VALUE));
726                 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
727                     minimumPasswordLength = Integer.parseInt(
728                             parser.getAttributeValue(null, ATTR_VALUE));
729                 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
730                     passwordHistoryLength = Integer.parseInt(
731                             parser.getAttributeValue(null, ATTR_VALUE));
732                 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
733                     minimumPasswordUpperCase = Integer.parseInt(
734                             parser.getAttributeValue(null, ATTR_VALUE));
735                 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
736                     minimumPasswordLowerCase = Integer.parseInt(
737                             parser.getAttributeValue(null, ATTR_VALUE));
738                 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
739                     minimumPasswordLetters = Integer.parseInt(
740                             parser.getAttributeValue(null, ATTR_VALUE));
741                 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
742                     minimumPasswordNumeric = Integer.parseInt(
743                             parser.getAttributeValue(null, ATTR_VALUE));
744                 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
745                     minimumPasswordSymbols = Integer.parseInt(
746                             parser.getAttributeValue(null, ATTR_VALUE));
747                 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
748                     minimumPasswordNonLetter = Integer.parseInt(
749                             parser.getAttributeValue(null, ATTR_VALUE));
750                 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
751                     maximumTimeToUnlock = Long.parseLong(
752                             parser.getAttributeValue(null, ATTR_VALUE));
753                 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
754                     maximumFailedPasswordsForWipe = Integer.parseInt(
755                             parser.getAttributeValue(null, ATTR_VALUE));
756                 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
757                     specifiesGlobalProxy = Boolean.parseBoolean(
758                             parser.getAttributeValue(null, ATTR_VALUE));
759                 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
760                     globalProxySpec =
761                         parser.getAttributeValue(null, ATTR_VALUE);
762                 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
763                     globalProxyExclusionList =
764                         parser.getAttributeValue(null, ATTR_VALUE);
765                 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
766                     passwordExpirationTimeout = Long.parseLong(
767                             parser.getAttributeValue(null, ATTR_VALUE));
768                 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
769                     passwordExpirationDate = Long.parseLong(
770                             parser.getAttributeValue(null, ATTR_VALUE));
771                 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
772                     encryptionRequested = Boolean.parseBoolean(
773                             parser.getAttributeValue(null, ATTR_VALUE));
774                 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
775                     disableCamera = Boolean.parseBoolean(
776                             parser.getAttributeValue(null, ATTR_VALUE));
777                 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
778                     disableCallerId = Boolean.parseBoolean(
779                             parser.getAttributeValue(null, ATTR_VALUE));
780                 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
781                     disableBluetoothContactSharing = Boolean.parseBoolean(parser
782                             .getAttributeValue(null, ATTR_VALUE));
783                 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
784                     disableScreenCapture = Boolean.parseBoolean(
785                             parser.getAttributeValue(null, ATTR_VALUE));
786                 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
787                     requireAutoTime= Boolean.parseBoolean(
788                             parser.getAttributeValue(null, ATTR_VALUE));
789                 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
790                     disabledKeyguardFeatures = Integer.parseInt(
791                             parser.getAttributeValue(null, ATTR_VALUE));
792                 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
793                     accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
794                 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
795                     trustAgentInfos = getAllTrustAgentInfos(parser, tag);
796                 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
797                     crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
798                 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
799                     permittedAccessiblityServices = readPackageList(parser, tag);
800                 } else if (TAG_PERMITTED_IMES.equals(tag)) {
801                     permittedInputMethods = readPackageList(parser, tag);
802                 } else {
803                     Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
804                     XmlUtils.skipCurrentTag(parser);
805                 }
806             }
807         }
808
809         private List<String> readPackageList(XmlPullParser parser,
810                 String tag) throws XmlPullParserException, IOException {
811             List<String> result = new ArrayList<String>();
812             int outerDepth = parser.getDepth();
813             int outerType;
814             while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
815                     && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
816                 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
817                     continue;
818                 }
819                 String outerTag = parser.getName();
820                 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
821                     String packageName = parser.getAttributeValue(null, ATTR_VALUE);
822                     if (packageName != null) {
823                         result.add(packageName);
824                     } else {
825                         Slog.w(LOG_TAG, "Package name missing under " + outerTag);
826                     }
827                 } else {
828                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
829                 }
830             }
831             return result;
832         }
833
834         private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
835                 throws XmlPullParserException, IOException {
836             int outerDepthDAM = parser.getDepth();
837             int typeDAM;
838             Set<String> result = new HashSet<String>();
839             while ((typeDAM=parser.next()) != END_DOCUMENT
840                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
841                 if (typeDAM == END_TAG || typeDAM == TEXT) {
842                     continue;
843                 }
844                 String tagDAM = parser.getName();
845                 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
846                     result.add(parser.getAttributeValue(null, ATTR_VALUE));
847                 } else {
848                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
849                 }
850             }
851             return result;
852         }
853
854         private HashMap<String, TrustAgentInfo> getAllTrustAgentInfos(
855                 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
856             int outerDepthDAM = parser.getDepth();
857             int typeDAM;
858             HashMap<String, TrustAgentInfo> result = new HashMap<String, TrustAgentInfo>();
859             while ((typeDAM=parser.next()) != END_DOCUMENT
860                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
861                 if (typeDAM == END_TAG || typeDAM == TEXT) {
862                     continue;
863                 }
864                 String tagDAM = parser.getName();
865                 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
866                     final String component = parser.getAttributeValue(null, ATTR_VALUE);
867                     final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
868                     result.put(component, trustAgentInfo);
869                 } else {
870                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
871                 }
872             }
873             return result;
874         }
875
876         private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
877                 throws XmlPullParserException, IOException  {
878             int outerDepthDAM = parser.getDepth();
879             int typeDAM;
880             TrustAgentInfo result = new TrustAgentInfo(null);
881             while ((typeDAM=parser.next()) != END_DOCUMENT
882                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
883                 if (typeDAM == END_TAG || typeDAM == TEXT) {
884                     continue;
885                 }
886                 String tagDAM = parser.getName();
887                 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
888                     PersistableBundle bundle = new PersistableBundle();
889                     bundle.restoreFromXml(parser);
890                     result.options = bundle;
891                 } else {
892                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
893                 }
894             }
895             return result;
896         }
897
898         private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
899                 throws XmlPullParserException, IOException  {
900             int outerDepthDAM = parser.getDepth();
901             int typeDAM;
902             ArrayList<String> result = null;
903             while ((typeDAM=parser.next()) != END_DOCUMENT
904                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
905                 if (typeDAM == END_TAG || typeDAM == TEXT) {
906                     continue;
907                 }
908                 String tagDAM = parser.getName();
909                 if (TAG_PROVIDER.equals(tagDAM)) {
910                     final String provider = parser.getAttributeValue(null, ATTR_VALUE);
911                     if (result == null) {
912                         result = new ArrayList<>();
913                     }
914                     result.add(provider);
915                 } else {
916                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
917                 }
918             }
919             return result;
920         }
921
922         void dump(String prefix, PrintWriter pw) {
923             pw.print(prefix); pw.print("uid="); pw.println(getUid());
924             pw.print(prefix); pw.println("policies:");
925             ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
926             if (pols != null) {
927                 for (int i=0; i<pols.size(); i++) {
928                     pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
929                 }
930             }
931             pw.print(prefix); pw.print("passwordQuality=0x");
932                     pw.println(Integer.toHexString(passwordQuality));
933             pw.print(prefix); pw.print("minimumPasswordLength=");
934                     pw.println(minimumPasswordLength);
935             pw.print(prefix); pw.print("passwordHistoryLength=");
936                     pw.println(passwordHistoryLength);
937             pw.print(prefix); pw.print("minimumPasswordUpperCase=");
938                     pw.println(minimumPasswordUpperCase);
939             pw.print(prefix); pw.print("minimumPasswordLowerCase=");
940                     pw.println(minimumPasswordLowerCase);
941             pw.print(prefix); pw.print("minimumPasswordLetters=");
942                     pw.println(minimumPasswordLetters);
943             pw.print(prefix); pw.print("minimumPasswordNumeric=");
944                     pw.println(minimumPasswordNumeric);
945             pw.print(prefix); pw.print("minimumPasswordSymbols=");
946                     pw.println(minimumPasswordSymbols);
947             pw.print(prefix); pw.print("minimumPasswordNonLetter=");
948                     pw.println(minimumPasswordNonLetter);
949             pw.print(prefix); pw.print("maximumTimeToUnlock=");
950                     pw.println(maximumTimeToUnlock);
951             pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
952                     pw.println(maximumFailedPasswordsForWipe);
953             pw.print(prefix); pw.print("specifiesGlobalProxy=");
954                     pw.println(specifiesGlobalProxy);
955             pw.print(prefix); pw.print("passwordExpirationTimeout=");
956                     pw.println(passwordExpirationTimeout);
957             pw.print(prefix); pw.print("passwordExpirationDate=");
958                     pw.println(passwordExpirationDate);
959             if (globalProxySpec != null) {
960                 pw.print(prefix); pw.print("globalProxySpec=");
961                         pw.println(globalProxySpec);
962             }
963             if (globalProxyExclusionList != null) {
964                 pw.print(prefix); pw.print("globalProxyEclusionList=");
965                         pw.println(globalProxyExclusionList);
966             }
967             pw.print(prefix); pw.print("encryptionRequested=");
968                     pw.println(encryptionRequested);
969             pw.print(prefix); pw.print("disableCamera=");
970                     pw.println(disableCamera);
971             pw.print(prefix); pw.print("disableCallerId=");
972                     pw.println(disableCallerId);
973             pw.print(prefix); pw.print("disableBluetoothContactSharing=");
974                     pw.println(disableBluetoothContactSharing);
975             pw.print(prefix); pw.print("disableScreenCapture=");
976                     pw.println(disableScreenCapture);
977             pw.print(prefix); pw.print("requireAutoTime=");
978                     pw.println(requireAutoTime);
979             pw.print(prefix); pw.print("disabledKeyguardFeatures=");
980                     pw.println(disabledKeyguardFeatures);
981             pw.print(prefix); pw.print("crossProfileWidgetProviders=");
982                     pw.println(crossProfileWidgetProviders);
983             if (!(permittedAccessiblityServices == null)) {
984                 pw.print(prefix); pw.print("permittedAccessibilityServices=");
985                         pw.println(permittedAccessiblityServices.toString());
986             }
987             if (!(permittedInputMethods == null)) {
988                 pw.print(prefix); pw.print("permittedInputMethods=");
989                         pw.println(permittedInputMethods.toString());
990             }
991         }
992     }
993
994     private void handlePackagesChanged(String packageName, int userHandle) {
995         boolean removed = false;
996         if (DBG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
997         DevicePolicyData policy = getUserData(userHandle);
998         IPackageManager pm = AppGlobals.getPackageManager();
999         synchronized (this) {
1000             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1001                 ActiveAdmin aa = policy.mAdminList.get(i);
1002                 try {
1003                     // If we're checking all packages or if the specific one we're checking matches,
1004                     // then check if the package and receiver still exist.
1005                     final String adminPackage = aa.info.getPackageName();
1006                     if (packageName == null || packageName.equals(adminPackage)) {
1007                         if (pm.getPackageInfo(adminPackage, 0, userHandle) == null
1008                                 || pm.getReceiverInfo(aa.info.getComponent(), 0, userHandle)
1009                                     == null) {
1010                             removed = true;
1011                             policy.mAdminList.remove(i);
1012                             policy.mAdminMap.remove(aa.info.getComponent());
1013                         }
1014                     }
1015                 } catch (RemoteException re) {
1016                     // Shouldn't happen
1017                 }
1018             }
1019             if (removed) {
1020                 validatePasswordOwnerLocked(policy);
1021                 syncDeviceCapabilitiesLocked(policy);
1022                 saveSettingsLocked(policy.mUserHandle);
1023             }
1024
1025             if (policy.mDelegatedCertInstallerPackage != null &&
1026                     (packageName == null
1027                     || packageName.equals(policy.mDelegatedCertInstallerPackage))) {
1028                 try {
1029                     // Check if delegated cert installer package is removed.
1030                     if (pm.getPackageInfo(
1031                             policy.mDelegatedCertInstallerPackage, 0, userHandle) == null) {
1032                         policy.mDelegatedCertInstallerPackage = null;
1033                         saveSettingsLocked(policy.mUserHandle);
1034                     }
1035                 } catch (RemoteException e) {
1036                     // Shouldn't happen
1037                 }
1038             }
1039         }
1040     }
1041
1042     /**
1043      * Instantiates the service.
1044      */
1045     public DevicePolicyManagerService(Context context) {
1046         mContext = context;
1047         mUserManager = UserManager.get(mContext);
1048         mHasFeature = context.getPackageManager().hasSystemFeature(
1049                 PackageManager.FEATURE_DEVICE_ADMIN);
1050         mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1051         mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
1052         mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DPM");
1053         mLocalService = new LocalService();
1054         if (!mHasFeature) {
1055             // Skip the rest of the initialization
1056             return;
1057         }
1058         IntentFilter filter = new IntentFilter();
1059         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1060         filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1061         filter.addAction(Intent.ACTION_USER_REMOVED);
1062         filter.addAction(Intent.ACTION_USER_STARTED);
1063         filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1064         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1065         context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1066         filter = new IntentFilter();
1067         filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1068         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1069         filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1070         filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1071         filter.addDataScheme("package");
1072         context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1073         filter = new IntentFilter();
1074         filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1075         context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1076
1077         LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1078     }
1079
1080     /**
1081      * Creates and loads the policy data from xml.
1082      * @param userHandle the user for whom to load the policy data
1083      * @return
1084      */
1085     DevicePolicyData getUserData(int userHandle) {
1086         synchronized (this) {
1087             DevicePolicyData policy = mUserData.get(userHandle);
1088             if (policy == null) {
1089                 policy = new DevicePolicyData(userHandle);
1090                 mUserData.append(userHandle, policy);
1091                 loadSettingsLocked(policy, userHandle);
1092             }
1093             return policy;
1094         }
1095     }
1096
1097     /**
1098      * Creates and loads the policy data from xml for data that is shared between
1099      * various profiles of a user. In contrast to {@link #getUserData(int)}
1100      * it allows access to data of users other than the calling user.
1101      *
1102      * This function should only be used for shared data, e.g. everything regarding
1103      * passwords and should be removed once multiple screen locks are present.
1104      * @param userHandle the user for whom to load the policy data
1105      * @return
1106      */
1107     DevicePolicyData getUserDataUnchecked(int userHandle) {
1108         long ident = Binder.clearCallingIdentity();
1109         try {
1110             return getUserData(userHandle);
1111         } finally {
1112             Binder.restoreCallingIdentity(ident);
1113         }
1114     }
1115
1116     void removeUserData(int userHandle) {
1117         synchronized (this) {
1118             if (userHandle == UserHandle.USER_OWNER) {
1119                 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1120                 return;
1121             }
1122             if (mDeviceOwner != null) {
1123                 mDeviceOwner.removeProfileOwner(userHandle);
1124                 mDeviceOwner.writeOwnerFile();
1125             }
1126
1127             DevicePolicyData policy = mUserData.get(userHandle);
1128             if (policy != null) {
1129                 mUserData.remove(userHandle);
1130             }
1131             File policyFile = new File(Environment.getUserSystemDirectory(userHandle),
1132                     DEVICE_POLICIES_XML);
1133             policyFile.delete();
1134             Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1135         }
1136         updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1137     }
1138
1139     void loadDeviceOwner() {
1140         synchronized (this) {
1141             mDeviceOwner = DeviceOwner.load();
1142             updateDeviceOwnerLocked();
1143         }
1144     }
1145
1146     /**
1147      * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1148      * reminders.  Clears alarm if no expirations are configured.
1149      */
1150     protected void setExpirationAlarmCheckLocked(Context context, DevicePolicyData policy) {
1151         final long expiration = getPasswordExpirationLocked(null, policy.mUserHandle);
1152         final long now = System.currentTimeMillis();
1153         final long timeToExpire = expiration - now;
1154         final long alarmTime;
1155         if (expiration == 0) {
1156             // No expirations are currently configured:  Cancel alarm.
1157             alarmTime = 0;
1158         } else if (timeToExpire <= 0) {
1159             // The password has already expired:  Repeat every 24 hours.
1160             alarmTime = now + MS_PER_DAY;
1161         } else {
1162             // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
1163             // the expiration time.
1164             long alarmInterval = timeToExpire % MS_PER_DAY;
1165             if (alarmInterval == 0) {
1166                 alarmInterval = MS_PER_DAY;
1167             }
1168             alarmTime = now + alarmInterval;
1169         }
1170
1171         long token = Binder.clearCallingIdentity();
1172         try {
1173             AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1174             PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1175                     new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1176                     PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1177                     new UserHandle(policy.mUserHandle));
1178             am.cancel(pi);
1179             if (alarmTime != 0) {
1180                 am.set(AlarmManager.RTC, alarmTime, pi);
1181             }
1182         } finally {
1183             Binder.restoreCallingIdentity(token);
1184         }
1185     }
1186
1187     private IWindowManager getWindowManager() {
1188         if (mIWindowManager == null) {
1189             IBinder b = ServiceManager.getService(Context.WINDOW_SERVICE);
1190             mIWindowManager = IWindowManager.Stub.asInterface(b);
1191         }
1192         return mIWindowManager;
1193     }
1194
1195     private NotificationManager getNotificationManager() {
1196         if (mNotificationManager == null) {
1197             mNotificationManager =
1198                     (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
1199         }
1200         return mNotificationManager;
1201     }
1202
1203     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1204         ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1205         if (admin != null
1206                 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1207                 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1208             return admin;
1209         }
1210         return null;
1211     }
1212
1213     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1214             throws SecurityException {
1215         final int callingUid = Binder.getCallingUid();
1216
1217         ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1218         if (result != null) {
1219             return result;
1220         }
1221
1222         if (who != null) {
1223             final int userId = UserHandle.getUserId(callingUid);
1224             final DevicePolicyData policy = getUserData(userId);
1225             ActiveAdmin admin = policy.mAdminMap.get(who);
1226             if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1227                 throw new SecurityException("Admin " + admin.info.getComponent()
1228                          + " does not own the device");
1229             }
1230             if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1231                 throw new SecurityException("Admin " + admin.info.getComponent()
1232                         + " does not own the profile");
1233             }
1234             throw new SecurityException("Admin " + admin.info.getComponent()
1235                     + " did not specify uses-policy for: "
1236                     + admin.info.getTagForPolicy(reqPolicy));
1237         } else {
1238             throw new SecurityException("No active admin owned by uid "
1239                     + Binder.getCallingUid() + " for policy #" + reqPolicy);
1240         }
1241     }
1242
1243     private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
1244             int uid) {
1245         // Try to find an admin which can use reqPolicy
1246         final int userId = UserHandle.getUserId(uid);
1247         final DevicePolicyData policy = getUserData(userId);
1248         if (who != null) {
1249             ActiveAdmin admin = policy.mAdminMap.get(who);
1250             if (admin == null) {
1251                 throw new SecurityException("No active admin " + who);
1252             }
1253             if (admin.getUid() != uid) {
1254                 throw new SecurityException("Admin " + who + " is not owned by uid "
1255                         + Binder.getCallingUid());
1256             }
1257             if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
1258                 return admin;
1259             }
1260         } else {
1261             for (ActiveAdmin admin : policy.mAdminList) {
1262                 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
1263                         userId)) {
1264                     return admin;
1265                 }
1266             }
1267         }
1268
1269         return null;
1270     }
1271
1272     private boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
1273             int userId) {
1274         boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
1275         boolean ownsProfile = (getProfileOwner(userId) != null
1276                 && getProfileOwner(userId).getPackageName()
1277                     .equals(admin.info.getPackageName()));
1278         boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName())
1279                 && !hasUserSetupCompleted(userId);
1280
1281         if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1282             if ((userId == UserHandle.USER_OWNER && (ownsDevice || ownsInitialization))
1283                     || (ownsDevice && ownsProfile)) {
1284                 return true;
1285             }
1286         } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1287             if ((userId == UserHandle.USER_OWNER && ownsDevice) || ownsProfile
1288                     || ownsInitialization) {
1289                 return true;
1290             }
1291         } else {
1292             if (admin.info.usesPolicy(reqPolicy)) {
1293                 return true;
1294             }
1295         }
1296         return false;
1297     }
1298
1299     void sendAdminCommandLocked(ActiveAdmin admin, String action) {
1300         sendAdminCommandLocked(admin, action, null);
1301     }
1302
1303     void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
1304         sendAdminCommandLocked(admin, action, null, result);
1305     }
1306
1307     /**
1308      * Send an update to one specific admin, get notified when that admin returns a result.
1309      */
1310     void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
1311             BroadcastReceiver result) {
1312         Intent intent = new Intent(action);
1313         intent.setComponent(admin.info.getComponent());
1314         if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
1315             intent.putExtra("expiration", admin.passwordExpirationDate);
1316         }
1317         if (adminExtras != null) {
1318             intent.putExtras(adminExtras);
1319         }
1320         if (result != null) {
1321             mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
1322                     null, result, mHandler, Activity.RESULT_OK, null, null);
1323         } else {
1324             mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
1325         }
1326     }
1327
1328     /**
1329      * Send an update to all admins of a user that enforce a specified policy.
1330      */
1331     void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
1332         final DevicePolicyData policy = getUserData(userHandle);
1333         final int count = policy.mAdminList.size();
1334         if (count > 0) {
1335             for (int i = 0; i < count; i++) {
1336                 final ActiveAdmin admin = policy.mAdminList.get(i);
1337                 if (admin.info.usesPolicy(reqPolicy)) {
1338                     sendAdminCommandLocked(admin, action);
1339                 }
1340             }
1341         }
1342     }
1343
1344     /**
1345      * Send an update intent to all admins of a user and its profiles. Only send to admins that
1346      * enforce a specified policy.
1347      */
1348     private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
1349             int userHandle) {
1350         List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1351         for (UserInfo ui : profiles) {
1352             int id = ui.id;
1353             sendAdminCommandLocked(action, reqPolicy, id);
1354         }
1355     }
1356
1357     void removeActiveAdminLocked(final ComponentName adminReceiver, int userHandle) {
1358         final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
1359         if (admin != null) {
1360             synchronized (this) {
1361                 getUserData(userHandle).mRemovingAdmins.add(adminReceiver);
1362             }
1363             sendAdminCommandLocked(admin,
1364                     DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
1365                     new BroadcastReceiver() {
1366                         @Override
1367                         public void onReceive(Context context, Intent intent) {
1368                             synchronized (DevicePolicyManagerService.this) {
1369                                 int userHandle = admin.getUserHandle().getIdentifier();
1370                                 DevicePolicyData policy = getUserData(userHandle);
1371                                 boolean doProxyCleanup = admin.info.usesPolicy(
1372                                         DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
1373                                 policy.mAdminList.remove(admin);
1374                                 policy.mAdminMap.remove(adminReceiver);
1375                                 validatePasswordOwnerLocked(policy);
1376                                 syncDeviceCapabilitiesLocked(policy);
1377                                 if (doProxyCleanup) {
1378                                     resetGlobalProxyLocked(getUserData(userHandle));
1379                                 }
1380                                 saveSettingsLocked(userHandle);
1381                                 updateMaximumTimeToLockLocked(policy);
1382                                 policy.mRemovingAdmins.remove(adminReceiver);
1383                             }
1384                         }
1385                     });
1386         }
1387     }
1388
1389     public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle) {
1390         if (!mHasFeature) {
1391             return null;
1392         }
1393         enforceCrossUserPermission(userHandle);
1394         Intent resolveIntent = new Intent();
1395         resolveIntent.setComponent(adminName);
1396         List<ResolveInfo> infos = mContext.getPackageManager().queryBroadcastReceivers(
1397                 resolveIntent,
1398                 PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
1399                 userHandle);
1400         if (infos == null || infos.size() <= 0) {
1401             throw new IllegalArgumentException("Unknown admin: " + adminName);
1402         }
1403
1404         try {
1405             return new DeviceAdminInfo(mContext, infos.get(0));
1406         } catch (XmlPullParserException e) {
1407             Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
1408                     e);
1409             return null;
1410         } catch (IOException e) {
1411             Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
1412                     e);
1413             return null;
1414         }
1415     }
1416
1417     private static JournaledFile makeJournaledFile(int userHandle) {
1418         final String base = userHandle == 0
1419                 ? "/data/system/" + DEVICE_POLICIES_XML
1420                 : new File(Environment.getUserSystemDirectory(userHandle), DEVICE_POLICIES_XML)
1421                         .getAbsolutePath();
1422         return new JournaledFile(new File(base), new File(base + ".tmp"));
1423     }
1424
1425     private void saveSettingsLocked(int userHandle) {
1426         DevicePolicyData policy = getUserData(userHandle);
1427         JournaledFile journal = makeJournaledFile(userHandle);
1428         FileOutputStream stream = null;
1429         try {
1430             stream = new FileOutputStream(journal.chooseForWrite(), false);
1431             XmlSerializer out = new FastXmlSerializer();
1432             out.setOutput(stream, StandardCharsets.UTF_8.name());
1433             out.startDocument(null, true);
1434
1435             out.startTag(null, "policies");
1436             if (policy.mRestrictionsProvider != null) {
1437                 out.attribute(null, ATTR_PERMISSION_PROVIDER,
1438                         policy.mRestrictionsProvider.flattenToString());
1439             }
1440             if (policy.mUserSetupComplete) {
1441                 out.attribute(null, ATTR_SETUP_COMPLETE,
1442                         Boolean.toString(true));
1443             }
1444             if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
1445                 out.attribute(null, ATTR_PERMISSION_POLICY,
1446                         Integer.toString(policy.mPermissionPolicy));
1447             }
1448             if (policy.mDelegatedCertInstallerPackage != null) {
1449                 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
1450                         policy.mDelegatedCertInstallerPackage);
1451             }
1452
1453             final int N = policy.mAdminList.size();
1454             for (int i=0; i<N; i++) {
1455                 ActiveAdmin ap = policy.mAdminList.get(i);
1456                 if (ap != null) {
1457                     out.startTag(null, "admin");
1458                     out.attribute(null, "name", ap.info.getComponent().flattenToString());
1459                     ap.writeToXml(out);
1460                     out.endTag(null, "admin");
1461                 }
1462             }
1463
1464             if (policy.mPasswordOwner >= 0) {
1465                 out.startTag(null, "password-owner");
1466                 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
1467                 out.endTag(null, "password-owner");
1468             }
1469
1470             if (policy.mFailedPasswordAttempts != 0) {
1471                 out.startTag(null, "failed-password-attempts");
1472                 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
1473                 out.endTag(null, "failed-password-attempts");
1474             }
1475
1476             if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
1477                     || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
1478                     || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
1479                     || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
1480                 out.startTag(null, "active-password");
1481                 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
1482                 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
1483                 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
1484                 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
1485                 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
1486                 out.attribute(null, "numeric", Integer
1487                         .toString(policy.mActivePasswordNumeric));
1488                 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
1489                 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
1490                 out.endTag(null, "active-password");
1491             }
1492
1493             for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
1494                 String component = policy.mLockTaskPackages.get(i);
1495                 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
1496                 out.attribute(null, "name", component);
1497                 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
1498             }
1499
1500             if (policy.mStatusBarDisabled) {
1501                 out.startTag(null, TAG_STATUS_BAR);
1502                 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
1503                 out.endTag(null, TAG_STATUS_BAR);
1504             }
1505
1506             if (policy.doNotAskCredentialsOnBoot) {
1507                 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
1508                 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
1509             }
1510
1511             out.endTag(null, "policies");
1512
1513             out.endDocument();
1514             stream.flush();
1515             FileUtils.sync(stream);
1516             stream.close();
1517             journal.commit();
1518             sendChangedNotification(userHandle);
1519         } catch (IOException e) {
1520             try {
1521                 if (stream != null) {
1522                     stream.close();
1523                 }
1524             } catch (IOException ex) {
1525                 // Ignore
1526             }
1527             journal.rollback();
1528         }
1529     }
1530
1531     private void sendChangedNotification(int userHandle) {
1532         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1533         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1534         long ident = Binder.clearCallingIdentity();
1535         try {
1536             mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
1537         } finally {
1538             Binder.restoreCallingIdentity(ident);
1539         }
1540     }
1541
1542     private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
1543         JournaledFile journal = makeJournaledFile(userHandle);
1544         FileInputStream stream = null;
1545         File file = journal.chooseForRead();
1546         try {
1547             stream = new FileInputStream(file);
1548             XmlPullParser parser = Xml.newPullParser();
1549             parser.setInput(stream, StandardCharsets.UTF_8.name());
1550
1551             int type;
1552             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1553                     && type != XmlPullParser.START_TAG) {
1554             }
1555             String tag = parser.getName();
1556             if (!"policies".equals(tag)) {
1557                 throw new XmlPullParserException(
1558                         "Settings do not start with policies tag: found " + tag);
1559             }
1560
1561             // Extract the permission provider component name if available
1562             String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
1563             if (permissionProvider != null) {
1564                 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
1565             }
1566             String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
1567             if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
1568                 policy.mUserSetupComplete = true;
1569             }
1570             String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
1571             if (!TextUtils.isEmpty(permissionPolicy)) {
1572                 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
1573             }
1574             policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
1575                     ATTR_DELEGATED_CERT_INSTALLER);
1576
1577             type = parser.next();
1578             int outerDepth = parser.getDepth();
1579             policy.mLockTaskPackages.clear();
1580             policy.mAdminList.clear();
1581             policy.mAdminMap.clear();
1582             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1583                    && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1584                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1585                     continue;
1586                 }
1587                 tag = parser.getName();
1588                 if ("admin".equals(tag)) {
1589                     String name = parser.getAttributeValue(null, "name");
1590                     try {
1591                         DeviceAdminInfo dai = findAdmin(
1592                                 ComponentName.unflattenFromString(name), userHandle);
1593                         if (DBG && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
1594                                 != userHandle)) {
1595                             Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
1596                                     + dai.getActivityInfo().applicationInfo.uid + " for user "
1597                                     + userHandle);
1598                         }
1599                         if (dai != null) {
1600                             ActiveAdmin ap = new ActiveAdmin(dai);
1601                             ap.readFromXml(parser);
1602                             policy.mAdminMap.put(ap.info.getComponent(), ap);
1603                         }
1604                     } catch (RuntimeException e) {
1605                         Slog.w(LOG_TAG, "Failed loading admin " + name, e);
1606                     }
1607                 } else if ("failed-password-attempts".equals(tag)) {
1608                     policy.mFailedPasswordAttempts = Integer.parseInt(
1609                             parser.getAttributeValue(null, "value"));
1610                 } else if ("password-owner".equals(tag)) {
1611                     policy.mPasswordOwner = Integer.parseInt(
1612                             parser.getAttributeValue(null, "value"));
1613                 } else if ("active-password".equals(tag)) {
1614                     policy.mActivePasswordQuality = Integer.parseInt(
1615                             parser.getAttributeValue(null, "quality"));
1616                     policy.mActivePasswordLength = Integer.parseInt(
1617                             parser.getAttributeValue(null, "length"));
1618                     policy.mActivePasswordUpperCase = Integer.parseInt(
1619                             parser.getAttributeValue(null, "uppercase"));
1620                     policy.mActivePasswordLowerCase = Integer.parseInt(
1621                             parser.getAttributeValue(null, "lowercase"));
1622                     policy.mActivePasswordLetters = Integer.parseInt(
1623                             parser.getAttributeValue(null, "letters"));
1624                     policy.mActivePasswordNumeric = Integer.parseInt(
1625                             parser.getAttributeValue(null, "numeric"));
1626                     policy.mActivePasswordSymbols = Integer.parseInt(
1627                             parser.getAttributeValue(null, "symbols"));
1628                     policy.mActivePasswordNonLetter = Integer.parseInt(
1629                             parser.getAttributeValue(null, "nonletter"));
1630                 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
1631                     policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
1632                 } else if (TAG_STATUS_BAR.equals(tag)) {
1633                     policy.mStatusBarDisabled = Boolean.parseBoolean(
1634                             parser.getAttributeValue(null, ATTR_DISABLED));
1635                 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
1636                     policy.doNotAskCredentialsOnBoot = true;
1637                 } else {
1638                     Slog.w(LOG_TAG, "Unknown tag: " + tag);
1639                     XmlUtils.skipCurrentTag(parser);
1640                 }
1641             }
1642         } catch (NullPointerException e) {
1643             Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1644         } catch (NumberFormatException e) {
1645             Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1646         } catch (XmlPullParserException e) {
1647             Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1648         } catch (FileNotFoundException e) {
1649             // Don't be noisy, this is normal if we haven't defined any policies.
1650         } catch (IOException e) {
1651             Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1652         } catch (IndexOutOfBoundsException e) {
1653             Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1654         }
1655         try {
1656             if (stream != null) {
1657                 stream.close();
1658             }
1659         } catch (IOException e) {
1660             // Ignore
1661         }
1662
1663         // Generate a list of admins from the admin map
1664         policy.mAdminList.addAll(policy.mAdminMap.values());
1665
1666         // Validate that what we stored for the password quality matches
1667         // sufficiently what is currently set.  Note that this is only
1668         // a sanity check in case the two get out of sync; this should
1669         // never normally happen.
1670         final long identity = Binder.clearCallingIdentity();
1671         try {
1672             LockPatternUtils utils = new LockPatternUtils(mContext);
1673             if (utils.getActivePasswordQuality(userHandle) < policy.mActivePasswordQuality) {
1674                 Slog.w(LOG_TAG, "Active password quality 0x"
1675                         + Integer.toHexString(policy.mActivePasswordQuality)
1676                         + " does not match actual quality 0x"
1677                         + Integer.toHexString(utils.getActivePasswordQuality(userHandle)));
1678                 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
1679                 policy.mActivePasswordLength = 0;
1680                 policy.mActivePasswordUpperCase = 0;
1681                 policy.mActivePasswordLowerCase = 0;
1682                 policy.mActivePasswordLetters = 0;
1683                 policy.mActivePasswordNumeric = 0;
1684                 policy.mActivePasswordSymbols = 0;
1685                 policy.mActivePasswordNonLetter = 0;
1686             }
1687         } finally {
1688             Binder.restoreCallingIdentity(identity);
1689         }
1690
1691         validatePasswordOwnerLocked(policy);
1692         syncDeviceCapabilitiesLocked(policy);
1693         updateMaximumTimeToLockLocked(policy);
1694         addDeviceInitializerToLockTaskPackagesLocked(userHandle);
1695         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
1696         if (policy.mStatusBarDisabled) {
1697             setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
1698         }
1699     }
1700
1701     private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
1702         IActivityManager am = ActivityManagerNative.getDefault();
1703         long ident = Binder.clearCallingIdentity();
1704         try {
1705             am.updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
1706         } catch (RemoteException e) {
1707             // Not gonna happen.
1708         } finally {
1709             Binder.restoreCallingIdentity(ident);
1710         }
1711     }
1712
1713     private void updateDeviceOwnerLocked() {
1714         IActivityManager am = ActivityManagerNative.getDefault();
1715         long ident = Binder.clearCallingIdentity();
1716         try {
1717             am.updateDeviceOwner(getDeviceOwner());
1718         } catch (RemoteException e) {
1719             // Not gonna happen.
1720         } finally {
1721             Binder.restoreCallingIdentity(ident);
1722         }
1723     }
1724
1725     static void validateQualityConstant(int quality) {
1726         switch (quality) {
1727             case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
1728             case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
1729             case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
1730             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
1731             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
1732             case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
1733             case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
1734             case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
1735                 return;
1736         }
1737         throw new IllegalArgumentException("Invalid quality constant: 0x"
1738                 + Integer.toHexString(quality));
1739     }
1740
1741     void validatePasswordOwnerLocked(DevicePolicyData policy) {
1742         if (policy.mPasswordOwner >= 0) {
1743             boolean haveOwner = false;
1744             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1745                 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
1746                     haveOwner = true;
1747                     break;
1748                 }
1749             }
1750             if (!haveOwner) {
1751                 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
1752                         + " no longer active; disabling");
1753                 policy.mPasswordOwner = -1;
1754             }
1755         }
1756     }
1757
1758     /**
1759      * Pushes down policy information to the system for any policies related to general device
1760      * capabilities that need to be enforced by lower level services (e.g. Camera services).
1761      */
1762     void syncDeviceCapabilitiesLocked(DevicePolicyData policy) {
1763         // Ensure the status of the camera is synced down to the system. Interested native services
1764         // should monitor this value and act accordingly.
1765         String cameraPropertyForUser = SYSTEM_PROP_DISABLE_CAMERA_PREFIX + policy.mUserHandle;
1766         boolean systemState = SystemProperties.getBoolean(cameraPropertyForUser, false);
1767         boolean cameraDisabled = getCameraDisabled(null, policy.mUserHandle);
1768         if (cameraDisabled != systemState) {
1769             long token = Binder.clearCallingIdentity();
1770             try {
1771                 String value = cameraDisabled ? "1" : "0";
1772                 if (DBG) Slog.v(LOG_TAG, "Change in camera state ["
1773                         + cameraPropertyForUser + "] = " + value);
1774                 SystemProperties.set(cameraPropertyForUser, value);
1775             } finally {
1776                 Binder.restoreCallingIdentity(token);
1777             }
1778         }
1779     }
1780
1781     public void systemReady() {
1782         if (!mHasFeature) {
1783             return;
1784         }
1785         getUserData(UserHandle.USER_OWNER);
1786         loadDeviceOwner();
1787         cleanUpOldUsers();
1788         // Register an observer for watching for user setup complete.
1789         new SetupContentObserver(mHandler).register(mContext.getContentResolver());
1790         // Initialize the user setup state, to handle the upgrade case.
1791         updateUserSetupComplete();
1792
1793         // Update the screen capture disabled cache in the window manager
1794         List<UserInfo> users = mUserManager.getUsers(true);
1795         final int N = users.size();
1796         for (int i = 0; i < N; i++) {
1797             int userHandle = users.get(i).id;
1798             updateScreenCaptureDisabledInWindowManager(userHandle,
1799                     getScreenCaptureDisabled(null, userHandle));
1800         }
1801     }
1802
1803     private void cleanUpOldUsers() {
1804         // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
1805         // before reboot
1806         Set<Integer> usersWithProfileOwners;
1807         Set<Integer> usersWithData;
1808         synchronized(this) {
1809             usersWithProfileOwners = mDeviceOwner != null
1810                     ? mDeviceOwner.getProfileOwnerKeys() : new HashSet<Integer>();
1811             usersWithData = new HashSet<Integer>();
1812             for (int i = 0; i < mUserData.size(); i++) {
1813                 usersWithData.add(mUserData.keyAt(i));
1814             }
1815         }
1816         List<UserInfo> allUsers = mUserManager.getUsers();
1817
1818         Set<Integer> deletedUsers = new HashSet<Integer>();
1819         deletedUsers.addAll(usersWithProfileOwners);
1820         deletedUsers.addAll(usersWithData);
1821         for (UserInfo userInfo : allUsers) {
1822             deletedUsers.remove(userInfo.id);
1823         }
1824         for (Integer userId : deletedUsers) {
1825             removeUserData(userId);
1826         }
1827     }
1828
1829     private void handlePasswordExpirationNotification(int userHandle) {
1830         synchronized (this) {
1831             final long now = System.currentTimeMillis();
1832
1833             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1834             for (UserInfo ui : profiles) {
1835                 int profileUserHandle = ui.id;
1836                 final DevicePolicyData policy = getUserData(profileUserHandle);
1837                 final int count = policy.mAdminList.size();
1838                 if (count > 0) {
1839                     for (int i = 0; i < count; i++) {
1840                         final ActiveAdmin admin = policy.mAdminList.get(i);
1841                         if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
1842                                 && admin.passwordExpirationTimeout > 0L
1843                                 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
1844                                 && admin.passwordExpirationDate > 0L) {
1845                             sendAdminCommandLocked(admin,
1846                                     DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
1847                         }
1848                     }
1849                 }
1850             }
1851             setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
1852         }
1853     }
1854
1855     private class MonitoringCertNotificationTask extends AsyncTask<Intent, Void, Void> {
1856         @Override
1857         protected Void doInBackground(Intent... params) {
1858             int userHandle = params[0].getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
1859
1860             if (userHandle == UserHandle.USER_ALL) {
1861                 for (UserInfo userInfo : mUserManager.getUsers()) {
1862                     manageNotification(userInfo.getUserHandle());
1863                 }
1864             } else {
1865                 manageNotification(new UserHandle(userHandle));
1866             }
1867             return null;
1868         }
1869
1870         private void manageNotification(UserHandle userHandle) {
1871             if (!mUserManager.isUserRunning(userHandle)) {
1872                 return;
1873             }
1874
1875             // Call out to KeyChain to check for user-added CAs
1876             boolean hasCert = false;
1877             try {
1878                 KeyChainConnection kcs = KeyChain.bindAsUser(mContext, userHandle);
1879                 try {
1880                     if (!kcs.getService().getUserCaAliases().getList().isEmpty()) {
1881                         hasCert = true;
1882                     }
1883                 } catch (RemoteException e) {
1884                     Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
1885                 } finally {
1886                     kcs.close();
1887                 }
1888             } catch (InterruptedException e) {
1889                 Thread.currentThread().interrupt();
1890             } catch (RuntimeException e) {
1891                 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
1892             }
1893             if (!hasCert) {
1894                 getNotificationManager().cancelAsUser(
1895                         null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
1896                 return;
1897             }
1898
1899             // Build and show a warning notification
1900             int smallIconId;
1901             String contentText;
1902             final String ownerName = getDeviceOwnerName();
1903             if (isManagedProfile(userHandle.getIdentifier())) {
1904                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_administrator);
1905                 smallIconId = R.drawable.stat_sys_certificate_info;
1906             } else if (ownerName != null) {
1907                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, ownerName);
1908                 smallIconId = R.drawable.stat_sys_certificate_info;
1909             } else {
1910                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
1911                 smallIconId = android.R.drawable.stat_sys_warning;
1912             }
1913
1914             Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
1915             dialogIntent.setFlags(
1916                     Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1917             dialogIntent.setPackage("com.android.settings");
1918             PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
1919                     dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, userHandle);
1920
1921             final Context userContext;
1922             try {
1923                 userContext = mContext.createPackageContextAsUser("android", 0, userHandle);
1924             } catch (PackageManager.NameNotFoundException e) {
1925                 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
1926                 return;
1927             }
1928             final Notification noti = new Notification.Builder(userContext)
1929                 .setSmallIcon(smallIconId)
1930                 .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning))
1931                 .setContentText(contentText)
1932                 .setContentIntent(notifyIntent)
1933                 .setPriority(Notification.PRIORITY_HIGH)
1934                 .setShowWhen(false)
1935                 .setColor(mContext.getColor(
1936                         com.android.internal.R.color.system_notification_accent_color))
1937                 .build();
1938
1939             getNotificationManager().notifyAsUser(
1940                     null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
1941         }
1942     }
1943
1944     /**
1945      * @param adminReceiver The admin to add
1946      * @param refreshing true = update an active admin, no error
1947      */
1948     @Override
1949     public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
1950         if (!mHasFeature) {
1951             return;
1952         }
1953         setActiveAdmin(adminReceiver, refreshing, userHandle, null);
1954     }
1955
1956     private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
1957             Bundle onEnableData) {
1958         mContext.enforceCallingOrSelfPermission(
1959                 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
1960         enforceCrossUserPermission(userHandle);
1961
1962         DevicePolicyData policy = getUserData(userHandle);
1963         DeviceAdminInfo info = findAdmin(adminReceiver, userHandle);
1964         if (info == null) {
1965             throw new IllegalArgumentException("Bad admin: " + adminReceiver);
1966         }
1967         synchronized (this) {
1968             long ident = Binder.clearCallingIdentity();
1969             try {
1970                 if (!refreshing
1971                         && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
1972                     throw new IllegalArgumentException("Admin is already added");
1973                 }
1974                 ActiveAdmin newAdmin = new ActiveAdmin(info);
1975                 policy.mAdminMap.put(adminReceiver, newAdmin);
1976                 int replaceIndex = -1;
1977                 final int N = policy.mAdminList.size();
1978                 for (int i=0; i < N; i++) {
1979                     ActiveAdmin oldAdmin = policy.mAdminList.get(i);
1980                     if (oldAdmin.info.getComponent().equals(adminReceiver)) {
1981                         replaceIndex = i;
1982                         break;
1983                     }
1984                 }
1985                 if (replaceIndex == -1) {
1986                     policy.mAdminList.add(newAdmin);
1987                     enableIfNecessary(info.getPackageName(), userHandle);
1988                 } else {
1989                     policy.mAdminList.set(replaceIndex, newAdmin);
1990                 }
1991                 saveSettingsLocked(userHandle);
1992                 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
1993                         onEnableData, null);
1994             } finally {
1995                 Binder.restoreCallingIdentity(ident);
1996             }
1997         }
1998     }
1999
2000     @Override
2001     public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2002         if (!mHasFeature) {
2003             return false;
2004         }
2005         enforceCrossUserPermission(userHandle);
2006         synchronized (this) {
2007             return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2008         }
2009     }
2010
2011     @Override
2012     public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2013         if (!mHasFeature) {
2014             return false;
2015         }
2016         enforceCrossUserPermission(userHandle);
2017         synchronized (this) {
2018             DevicePolicyData policyData = getUserData(userHandle);
2019             return policyData.mRemovingAdmins.contains(adminReceiver);
2020         }
2021     }
2022
2023     @Override
2024     public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2025         if (!mHasFeature) {
2026             return false;
2027         }
2028         enforceCrossUserPermission(userHandle);
2029         synchronized (this) {
2030             ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2031             if (administrator == null) {
2032                 throw new SecurityException("No active admin " + adminReceiver);
2033             }
2034             return administrator.info.usesPolicy(policyId);
2035         }
2036     }
2037
2038     @Override
2039     @SuppressWarnings("unchecked")
2040     public List<ComponentName> getActiveAdmins(int userHandle) {
2041         if (!mHasFeature) {
2042             return Collections.EMPTY_LIST;
2043         }
2044
2045         enforceCrossUserPermission(userHandle);
2046         synchronized (this) {
2047             DevicePolicyData policy = getUserData(userHandle);
2048             final int N = policy.mAdminList.size();
2049             if (N <= 0) {
2050                 return null;
2051             }
2052             ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2053             for (int i=0; i<N; i++) {
2054                 res.add(policy.mAdminList.get(i).info.getComponent());
2055             }
2056             return res;
2057         }
2058     }
2059
2060     @Override
2061     public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2062         if (!mHasFeature) {
2063             return false;
2064         }
2065         enforceCrossUserPermission(userHandle);
2066         synchronized (this) {
2067             DevicePolicyData policy = getUserData(userHandle);
2068             final int N = policy.mAdminList.size();
2069             for (int i=0; i<N; i++) {
2070                 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2071                     return true;
2072                 }
2073             }
2074             return false;
2075         }
2076     }
2077
2078     @Override
2079     public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
2080         if (!mHasFeature) {
2081             return;
2082         }
2083         enforceCrossUserPermission(userHandle);
2084         synchronized (this) {
2085             ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2086             if (admin == null) {
2087                 return;
2088             }
2089             if (admin.getUid() != Binder.getCallingUid()) {
2090                 // Active device owners must remain active admins.
2091                 if (isDeviceOwner(adminReceiver.getPackageName())) {
2092                     return;
2093                 }
2094                 mContext.enforceCallingOrSelfPermission(
2095                         android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2096             }
2097             long ident = Binder.clearCallingIdentity();
2098             try {
2099                 removeActiveAdminLocked(adminReceiver, userHandle);
2100             } finally {
2101                 Binder.restoreCallingIdentity(ident);
2102             }
2103         }
2104     }
2105
2106     @Override
2107     public void setPasswordQuality(ComponentName who, int quality) {
2108         if (!mHasFeature) {
2109             return;
2110         }
2111         Preconditions.checkNotNull(who, "ComponentName is null");
2112         final int userHandle = UserHandle.getCallingUserId();
2113         validateQualityConstant(quality);
2114
2115         synchronized (this) {
2116             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2117                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2118             if (ap.passwordQuality != quality) {
2119                 ap.passwordQuality = quality;
2120                 saveSettingsLocked(userHandle);
2121             }
2122         }
2123     }
2124
2125     @Override
2126     public int getPasswordQuality(ComponentName who, int userHandle) {
2127         if (!mHasFeature) {
2128             return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2129         }
2130         enforceCrossUserPermission(userHandle);
2131         synchronized (this) {
2132             int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2133
2134             if (who != null) {
2135                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2136                 return admin != null ? admin.passwordQuality : mode;
2137             }
2138
2139             // Return strictest policy for this user and profiles that are visible from this user.
2140             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2141             for (UserInfo userInfo : profiles) {
2142                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2143                 final int N = policy.mAdminList.size();
2144                 for (int i=0; i<N; i++) {
2145                     ActiveAdmin admin = policy.mAdminList.get(i);
2146                     if (mode < admin.passwordQuality) {
2147                         mode = admin.passwordQuality;
2148                     }
2149                 }
2150             }
2151             return mode;
2152         }
2153     }
2154
2155     @Override
2156     public void setPasswordMinimumLength(ComponentName who, int length) {
2157         if (!mHasFeature) {
2158             return;
2159         }
2160         Preconditions.checkNotNull(who, "ComponentName is null");
2161         final int userHandle = UserHandle.getCallingUserId();
2162         synchronized (this) {
2163             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2164                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2165             if (ap.minimumPasswordLength != length) {
2166                 ap.minimumPasswordLength = length;
2167                 saveSettingsLocked(userHandle);
2168             }
2169         }
2170     }
2171
2172     @Override
2173     public int getPasswordMinimumLength(ComponentName who, int userHandle) {
2174         if (!mHasFeature) {
2175             return 0;
2176         }
2177         enforceCrossUserPermission(userHandle);
2178         synchronized (this) {
2179             int length = 0;
2180
2181             if (who != null) {
2182                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2183                 return admin != null ? admin.minimumPasswordLength : length;
2184             }
2185
2186             // Return strictest policy for this user and profiles that are visible from this user.
2187             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2188             for (UserInfo userInfo : profiles) {
2189                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2190                 final int N = policy.mAdminList.size();
2191                 for (int i=0; i<N; i++) {
2192                     ActiveAdmin admin = policy.mAdminList.get(i);
2193                     if (length < admin.minimumPasswordLength) {
2194                         length = admin.minimumPasswordLength;
2195                     }
2196                 }
2197             }
2198             return length;
2199         }
2200     }
2201
2202     @Override
2203     public void setPasswordHistoryLength(ComponentName who, int length) {
2204         if (!mHasFeature) {
2205             return;
2206         }
2207         Preconditions.checkNotNull(who, "ComponentName is null");
2208         final int userHandle = UserHandle.getCallingUserId();
2209         synchronized (this) {
2210             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2211                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2212             if (ap.passwordHistoryLength != length) {
2213                 ap.passwordHistoryLength = length;
2214                 saveSettingsLocked(userHandle);
2215             }
2216         }
2217     }
2218
2219     @Override
2220     public int getPasswordHistoryLength(ComponentName who, int userHandle) {
2221         if (!mHasFeature) {
2222             return 0;
2223         }
2224         enforceCrossUserPermission(userHandle);
2225         synchronized (this) {
2226             int length = 0;
2227
2228             if (who != null) {
2229                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2230                 return admin != null ? admin.passwordHistoryLength : length;
2231             }
2232
2233             // Return strictest policy for this user and profiles that are visible from this user.
2234             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2235             for (UserInfo userInfo : profiles) {
2236                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2237                 final int N = policy.mAdminList.size();
2238                 for (int i = 0; i < N; i++) {
2239                     ActiveAdmin admin = policy.mAdminList.get(i);
2240                     if (length < admin.passwordHistoryLength) {
2241                         length = admin.passwordHistoryLength;
2242                     }
2243                 }
2244             }
2245             return length;
2246         }
2247     }
2248
2249     @Override
2250     public void setPasswordExpirationTimeout(ComponentName who, long timeout) {
2251         if (!mHasFeature) {
2252             return;
2253         }
2254         Preconditions.checkNotNull(who, "ComponentName is null");
2255         Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
2256         final int userHandle = UserHandle.getCallingUserId();
2257         synchronized (this) {
2258             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2259                     DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
2260             // Calling this API automatically bumps the expiration date
2261             final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
2262             ap.passwordExpirationDate = expiration;
2263             ap.passwordExpirationTimeout = timeout;
2264             if (timeout > 0L) {
2265                 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
2266                         + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
2267                         .format(new Date(expiration)));
2268             }
2269             saveSettingsLocked(userHandle);
2270             // in case this is the first one
2271             setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
2272         }
2273     }
2274
2275     /**
2276      * Return a single admin's expiration cycle time, or the min of all cycle times.
2277      * Returns 0 if not configured.
2278      */
2279     @Override
2280     public long getPasswordExpirationTimeout(ComponentName who, int userHandle) {
2281         if (!mHasFeature) {
2282             return 0L;
2283         }
2284         enforceCrossUserPermission(userHandle);
2285         synchronized (this) {
2286             long timeout = 0L;
2287
2288             if (who != null) {
2289                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2290                 return admin != null ? admin.passwordExpirationTimeout : timeout;
2291             }
2292
2293             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2294             for (UserInfo userInfo : profiles) {
2295                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2296                 final int N = policy.mAdminList.size();
2297                 for (int i = 0; i < N; i++) {
2298                     ActiveAdmin admin = policy.mAdminList.get(i);
2299                     if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
2300                             && timeout > admin.passwordExpirationTimeout)) {
2301                         timeout = admin.passwordExpirationTimeout;
2302                     }
2303                 }
2304             }
2305             return timeout;
2306         }
2307     }
2308
2309     @Override
2310     public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
2311         final int userId = UserHandle.getCallingUserId();
2312         List<String> changedProviders = null;
2313
2314         synchronized (this) {
2315             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2316                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2317             if (activeAdmin.crossProfileWidgetProviders == null) {
2318                 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
2319             }
2320             List<String> providers = activeAdmin.crossProfileWidgetProviders;
2321             if (!providers.contains(packageName)) {
2322                 providers.add(packageName);
2323                 changedProviders = new ArrayList<>(providers);
2324                 saveSettingsLocked(userId);
2325             }
2326         }
2327
2328         if (changedProviders != null) {
2329             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
2330             return true;
2331         }
2332
2333         return false;
2334     }
2335
2336     @Override
2337     public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
2338         final int userId = UserHandle.getCallingUserId();
2339         List<String> changedProviders = null;
2340
2341         synchronized (this) {
2342             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2343                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2344             if (activeAdmin.crossProfileWidgetProviders == null) {
2345                 return false;
2346             }
2347             List<String> providers = activeAdmin.crossProfileWidgetProviders;
2348             if (providers.remove(packageName)) {
2349                 changedProviders = new ArrayList<>(providers);
2350                 saveSettingsLocked(userId);
2351             }
2352         }
2353
2354         if (changedProviders != null) {
2355             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
2356             return true;
2357         }
2358
2359         return false;
2360     }
2361
2362     @Override
2363     public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
2364         synchronized (this) {
2365             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2366                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2367             if (activeAdmin.crossProfileWidgetProviders == null
2368                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
2369                 return null;
2370             }
2371             if (Binder.getCallingUid() == Process.myUid()) {
2372                 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
2373             } else {
2374                 return activeAdmin.crossProfileWidgetProviders;
2375             }
2376         }
2377     }
2378
2379     /**
2380      * Return a single admin's expiration date/time, or the min (soonest) for all admins.
2381      * Returns 0 if not configured.
2382      */
2383     private long getPasswordExpirationLocked(ComponentName who, int userHandle) {
2384         long timeout = 0L;
2385
2386         if (who != null) {
2387             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2388             return admin != null ? admin.passwordExpirationDate : timeout;
2389         }
2390
2391         List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2392         for (UserInfo userInfo : profiles) {
2393             DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2394             final int N = policy.mAdminList.size();
2395             for (int i = 0; i < N; i++) {
2396                 ActiveAdmin admin = policy.mAdminList.get(i);
2397                 if (timeout == 0L || (admin.passwordExpirationDate != 0
2398                         && timeout > admin.passwordExpirationDate)) {
2399                     timeout = admin.passwordExpirationDate;
2400                 }
2401             }
2402         }
2403         return timeout;
2404     }
2405
2406     @Override
2407     public long getPasswordExpiration(ComponentName who, int userHandle) {
2408         if (!mHasFeature) {
2409             return 0L;
2410         }
2411         enforceCrossUserPermission(userHandle);
2412         synchronized (this) {
2413             return getPasswordExpirationLocked(who, userHandle);
2414         }
2415     }
2416
2417     @Override
2418     public void setPasswordMinimumUpperCase(ComponentName who, int length) {
2419         if (!mHasFeature) {
2420             return;
2421         }
2422         Preconditions.checkNotNull(who, "ComponentName is null");
2423         final int userHandle = UserHandle.getCallingUserId();
2424         synchronized (this) {
2425             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2426                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2427             if (ap.minimumPasswordUpperCase != length) {
2428                 ap.minimumPasswordUpperCase = length;
2429                 saveSettingsLocked(userHandle);
2430             }
2431         }
2432     }
2433
2434     @Override
2435     public int getPasswordMinimumUpperCase(ComponentName who, int userHandle) {
2436         if (!mHasFeature) {
2437             return 0;
2438         }
2439         enforceCrossUserPermission(userHandle);
2440         synchronized (this) {
2441             int length = 0;
2442
2443             if (who != null) {
2444                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2445                 return admin != null ? admin.minimumPasswordUpperCase : length;
2446             }
2447
2448             // Return strictest policy for this user and profiles that are visible from this user.
2449             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2450             for (UserInfo userInfo : profiles) {
2451                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2452                 final int N = policy.mAdminList.size();
2453                 for (int i=0; i<N; i++) {
2454                     ActiveAdmin admin = policy.mAdminList.get(i);
2455                     if (length < admin.minimumPasswordUpperCase) {
2456                         length = admin.minimumPasswordUpperCase;
2457                     }
2458                 }
2459             }
2460             return length;
2461         }
2462     }
2463
2464     @Override
2465     public void setPasswordMinimumLowerCase(ComponentName who, int length) {
2466         Preconditions.checkNotNull(who, "ComponentName is null");
2467         final int userHandle = UserHandle.getCallingUserId();
2468         synchronized (this) {
2469             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2470                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2471             if (ap.minimumPasswordLowerCase != length) {
2472                 ap.minimumPasswordLowerCase = length;
2473                 saveSettingsLocked(userHandle);
2474             }
2475         }
2476     }
2477
2478     @Override
2479     public int getPasswordMinimumLowerCase(ComponentName who, int userHandle) {
2480         if (!mHasFeature) {
2481             return 0;
2482         }
2483         enforceCrossUserPermission(userHandle);
2484         synchronized (this) {
2485             int length = 0;
2486
2487             if (who != null) {
2488                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2489                 return admin != null ? admin.minimumPasswordLowerCase : length;
2490             }
2491
2492             // Return strictest policy for this user and profiles that are visible from this user.
2493             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2494             for (UserInfo userInfo : profiles) {
2495                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2496                 final int N = policy.mAdminList.size();
2497                 for (int i=0; i<N; i++) {
2498                     ActiveAdmin admin = policy.mAdminList.get(i);
2499                     if (length < admin.minimumPasswordLowerCase) {
2500                         length = admin.minimumPasswordLowerCase;
2501                     }
2502                 }
2503             }
2504             return length;
2505         }
2506     }
2507
2508     @Override
2509     public void setPasswordMinimumLetters(ComponentName who, int length) {
2510         if (!mHasFeature) {
2511             return;
2512         }
2513         Preconditions.checkNotNull(who, "ComponentName is null");
2514         final int userHandle = UserHandle.getCallingUserId();
2515         synchronized (this) {
2516             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2517                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2518             if (ap.minimumPasswordLetters != length) {
2519                 ap.minimumPasswordLetters = length;
2520                 saveSettingsLocked(userHandle);
2521             }
2522         }
2523     }
2524
2525     @Override
2526     public int getPasswordMinimumLetters(ComponentName who, int userHandle) {
2527         if (!mHasFeature) {
2528             return 0;
2529         }
2530         enforceCrossUserPermission(userHandle);
2531         synchronized (this) {
2532             int length = 0;
2533
2534             if (who != null) {
2535                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2536                 return admin != null ? admin.minimumPasswordLetters : length;
2537             }
2538
2539             // Return strictest policy for this user and profiles that are visible from this user.
2540             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2541             for (UserInfo userInfo : profiles) {
2542                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2543                 final int N = policy.mAdminList.size();
2544                 for (int i=0; i<N; i++) {
2545                     ActiveAdmin admin = policy.mAdminList.get(i);
2546                     if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2547                         continue;
2548                     }
2549                     if (length < admin.minimumPasswordLetters) {
2550                         length = admin.minimumPasswordLetters;
2551                     }
2552                 }
2553             }
2554             return length;
2555         }
2556     }
2557
2558     @Override
2559     public void setPasswordMinimumNumeric(ComponentName who, int length) {
2560         if (!mHasFeature) {
2561             return;
2562         }
2563         Preconditions.checkNotNull(who, "ComponentName is null");
2564         final int userHandle = UserHandle.getCallingUserId();
2565         synchronized (this) {
2566             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2567                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2568             if (ap.minimumPasswordNumeric != length) {
2569                 ap.minimumPasswordNumeric = length;
2570                 saveSettingsLocked(userHandle);
2571             }
2572         }
2573     }
2574
2575     @Override
2576     public int getPasswordMinimumNumeric(ComponentName who, int userHandle) {
2577         if (!mHasFeature) {
2578             return 0;
2579         }
2580         enforceCrossUserPermission(userHandle);
2581         synchronized (this) {
2582             int length = 0;
2583
2584             if (who != null) {
2585                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2586                 return admin != null ? admin.minimumPasswordNumeric : length;
2587             }
2588
2589             // Return strictest policy for this user and profiles that are visible from this user.
2590             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2591             for (UserInfo userInfo : profiles) {
2592                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2593                 final int N = policy.mAdminList.size();
2594                 for (int i = 0; i < N; i++) {
2595                     ActiveAdmin admin = policy.mAdminList.get(i);
2596                     if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2597                         continue;
2598                     }
2599                     if (length < admin.minimumPasswordNumeric) {
2600                         length = admin.minimumPasswordNumeric;
2601                     }
2602                 }
2603             }
2604             return length;
2605         }
2606     }
2607
2608     @Override
2609     public void setPasswordMinimumSymbols(ComponentName who, int length) {
2610         if (!mHasFeature) {
2611             return;
2612         }
2613         Preconditions.checkNotNull(who, "ComponentName is null");
2614         final int userHandle = UserHandle.getCallingUserId();
2615         synchronized (this) {
2616             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2617                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2618             if (ap.minimumPasswordSymbols != length) {
2619                 ap.minimumPasswordSymbols = length;
2620                 saveSettingsLocked(userHandle);
2621             }
2622         }
2623     }
2624
2625     @Override
2626     public int getPasswordMinimumSymbols(ComponentName who, int userHandle) {
2627         if (!mHasFeature) {
2628             return 0;
2629         }
2630         enforceCrossUserPermission(userHandle);
2631         synchronized (this) {
2632             int length = 0;
2633
2634             if (who != null) {
2635                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2636                 return admin != null ? admin.minimumPasswordSymbols : length;
2637             }
2638
2639             // Return strictest policy for this user and profiles that are visible from this user.
2640             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2641             for (UserInfo userInfo : profiles) {
2642                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2643                 final int N = policy.mAdminList.size();
2644                 for (int i=0; i<N; i++) {
2645                     ActiveAdmin admin = policy.mAdminList.get(i);
2646                     if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2647                         continue;
2648                     }
2649                     if (length < admin.minimumPasswordSymbols) {
2650                         length = admin.minimumPasswordSymbols;
2651                     }
2652                 }
2653             }
2654             return length;
2655         }
2656     }
2657
2658     @Override
2659     public void setPasswordMinimumNonLetter(ComponentName who, int length) {
2660         if (!mHasFeature) {
2661             return;
2662         }
2663         Preconditions.checkNotNull(who, "ComponentName is null");
2664         final int userHandle = UserHandle.getCallingUserId();
2665         synchronized (this) {
2666             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2667                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2668             if (ap.minimumPasswordNonLetter != length) {
2669                 ap.minimumPasswordNonLetter = length;
2670                 saveSettingsLocked(userHandle);
2671             }
2672         }
2673     }
2674
2675     @Override
2676     public int getPasswordMinimumNonLetter(ComponentName who, int userHandle) {
2677         if (!mHasFeature) {
2678             return 0;
2679         }
2680         enforceCrossUserPermission(userHandle);
2681         synchronized (this) {
2682             int length = 0;
2683
2684             if (who != null) {
2685                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2686                 return admin != null ? admin.minimumPasswordNonLetter : length;
2687             }
2688
2689             // Return strictest policy for this user and profiles that are visible from this user.
2690             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2691             for (UserInfo userInfo : profiles) {
2692                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2693                 final int N = policy.mAdminList.size();
2694                 for (int i=0; i<N; i++) {
2695                     ActiveAdmin admin = policy.mAdminList.get(i);
2696                     if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2697                         continue;
2698                     }
2699                     if (length < admin.minimumPasswordNonLetter) {
2700                         length = admin.minimumPasswordNonLetter;
2701                     }
2702                 }
2703             }
2704             return length;
2705         }
2706     }
2707
2708     @Override
2709     public boolean isActivePasswordSufficient(int userHandle) {
2710         if (!mHasFeature) {
2711             return true;
2712         }
2713         enforceCrossUserPermission(userHandle);
2714
2715         synchronized (this) {
2716
2717             // The active password is stored in the user that runs the launcher
2718             // If the user this is called from is part of a profile group, that is the parent
2719             // of the group.
2720             UserInfo parent = getProfileParent(userHandle);
2721             int id = (parent == null) ? userHandle : parent.id;
2722             DevicePolicyData policy = getUserDataUnchecked(id);
2723
2724             // This API can only be called by an active device admin,
2725             // so try to retrieve it to check that the caller is one.
2726             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2727             if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle)
2728                     || policy.mActivePasswordLength < getPasswordMinimumLength(null, userHandle)) {
2729                 return false;
2730             }
2731             if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2732                 return true;
2733             }
2734             return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(null, userHandle)
2735                 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(null, userHandle)
2736                 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(null, userHandle)
2737                 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(null, userHandle)
2738                 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(null, userHandle)
2739                 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(null, userHandle);
2740         }
2741     }
2742
2743     @Override
2744     public int getCurrentFailedPasswordAttempts(int userHandle) {
2745         synchronized (this) {
2746             // This API can only be called by an active device admin,
2747             // so try to retrieve it to check that the caller is one.
2748             getActiveAdminForCallerLocked(null,
2749                     DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2750
2751             // The active password is stored in the parent.
2752             UserInfo parent = getProfileParent(userHandle);
2753             int id = (parent == null) ? userHandle : parent.id;
2754             DevicePolicyData policy = getUserDataUnchecked(id);
2755
2756             return policy.mFailedPasswordAttempts;
2757         }
2758     }
2759
2760     @Override
2761     public void setMaximumFailedPasswordsForWipe(ComponentName who, int num) {
2762         if (!mHasFeature) {
2763             return;
2764         }
2765         Preconditions.checkNotNull(who, "ComponentName is null");
2766         final int userHandle = UserHandle.getCallingUserId();
2767         synchronized (this) {
2768             // This API can only be called by an active device admin,
2769             // so try to retrieve it to check that the caller is one.
2770             getActiveAdminForCallerLocked(who,
2771                     DeviceAdminInfo.USES_POLICY_WIPE_DATA);
2772             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2773                     DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2774             if (ap.maximumFailedPasswordsForWipe != num) {
2775                 ap.maximumFailedPasswordsForWipe = num;
2776                 saveSettingsLocked(userHandle);
2777             }
2778         }
2779     }
2780
2781     @Override
2782     public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle) {
2783         if (!mHasFeature) {
2784             return 0;
2785         }
2786         enforceCrossUserPermission(userHandle);
2787         synchronized (this) {
2788             ActiveAdmin admin = (who != null) ? getActiveAdminUncheckedLocked(who, userHandle)
2789                     : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
2790             return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
2791         }
2792     }
2793
2794     @Override
2795     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
2796         if (!mHasFeature) {
2797             return UserHandle.USER_NULL;
2798         }
2799         enforceCrossUserPermission(userHandle);
2800         synchronized (this) {
2801             ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
2802             return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
2803         }
2804     }
2805
2806     /**
2807      * Returns the admin with the strictest policy on maximum failed passwords for this user and all
2808      * profiles that are visible from this user. If the policy for the primary and any other profile
2809      * are equal, it returns the admin for the primary profile.
2810      * Returns {@code null} if none of them have that policy set.
2811      */
2812     private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(int userHandle) {
2813         int count = 0;
2814         ActiveAdmin strictestAdmin = null;
2815         for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
2816             DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2817             for (ActiveAdmin admin : policy.mAdminList) {
2818                 if (admin.maximumFailedPasswordsForWipe ==
2819                         ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
2820                     continue;  // No max number of failed passwords policy set for this profile.
2821                 }
2822
2823                 // We always favor the primary profile if several profiles have the same value set.
2824                 if (count == 0 ||
2825                         count > admin.maximumFailedPasswordsForWipe ||
2826                         (userInfo.isPrimary() && count >= admin.maximumFailedPasswordsForWipe)) {
2827                     count = admin.maximumFailedPasswordsForWipe;
2828                     strictestAdmin = admin;
2829                 }
2830             }
2831         }
2832         return strictestAdmin;
2833     }
2834
2835     @Override
2836     public boolean resetPassword(String passwordOrNull, int flags) {
2837         if (!mHasFeature) {
2838             return false;
2839         }
2840         final int userHandle = UserHandle.getCallingUserId();
2841         enforceNotManagedProfile(userHandle, "reset the password");
2842
2843         String password = passwordOrNull != null ? passwordOrNull : "";
2844
2845         int quality;
2846         synchronized (this) {
2847             // This api can only be called by an active device admin,
2848             // so try to retrieve it to check that the caller is one.
2849             getActiveAdminForCallerLocked(null,
2850                     DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
2851             quality = getPasswordQuality(null, userHandle);
2852             if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
2853                 int realQuality = LockPatternUtils.computePasswordQuality(password);
2854                 if (realQuality < quality
2855                         && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2856                     Slog.w(LOG_TAG, "resetPassword: password quality 0x"
2857                             + Integer.toHexString(realQuality)
2858                             + " does not meet required quality 0x"
2859                             + Integer.toHexString(quality));
2860                     return false;
2861                 }
2862                 quality = Math.max(realQuality, quality);
2863             }
2864             int length = getPasswordMinimumLength(null, userHandle);
2865             if (password.length() < length) {
2866                 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
2867                         + " does not meet required length " + length);
2868                 return false;
2869             }
2870             if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2871                 int letters = 0;
2872                 int uppercase = 0;
2873                 int lowercase = 0;
2874                 int numbers = 0;
2875                 int symbols = 0;
2876                 int nonletter = 0;
2877                 for (int i = 0; i < password.length(); i++) {
2878                     char c = password.charAt(i);
2879                     if (c >= 'A' && c <= 'Z') {
2880                         letters++;
2881                         uppercase++;
2882                     } else if (c >= 'a' && c <= 'z') {
2883                         letters++;
2884                         lowercase++;
2885                     } else if (c >= '0' && c <= '9') {
2886                         numbers++;
2887                         nonletter++;
2888                     } else {
2889                         symbols++;
2890                         nonletter++;
2891                     }
2892                 }
2893                 int neededLetters = getPasswordMinimumLetters(null, userHandle);
2894                 if(letters < neededLetters) {
2895                     Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
2896                             + " does not meet required number of letters " + neededLetters);
2897                     return false;
2898                 }
2899                 int neededNumbers = getPasswordMinimumNumeric(null, userHandle);
2900                 if (numbers < neededNumbers) {
2901                     Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
2902                             + " does not meet required number of numerical digits "
2903                             + neededNumbers);
2904                     return false;
2905                 }
2906                 int neededLowerCase = getPasswordMinimumLowerCase(null, userHandle);
2907                 if (lowercase < neededLowerCase) {
2908                     Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
2909                             + " does not meet required number of lowercase letters "
2910                             + neededLowerCase);
2911                     return false;
2912                 }
2913                 int neededUpperCase = getPasswordMinimumUpperCase(null, userHandle);
2914                 if (uppercase < neededUpperCase) {
2915                     Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
2916                             + " does not meet required number of uppercase letters "
2917                             + neededUpperCase);
2918                     return false;
2919                 }
2920                 int neededSymbols = getPasswordMinimumSymbols(null, userHandle);
2921                 if (symbols < neededSymbols) {
2922                     Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
2923                             + " does not meet required number of special symbols " + neededSymbols);
2924                     return false;
2925                 }
2926                 int neededNonLetter = getPasswordMinimumNonLetter(null, userHandle);
2927                 if (nonletter < neededNonLetter) {
2928                     Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
2929                             + " does not meet required number of non-letter characters "
2930                             + neededNonLetter);
2931                     return false;
2932                 }
2933             }
2934         }
2935
2936         int callingUid = Binder.getCallingUid();
2937         DevicePolicyData policy = getUserData(userHandle);
2938         if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
2939             Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
2940             return false;
2941         }
2942
2943         boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwnerOrInitializer(callingUid);
2944         boolean doNotAskCredentialsOnBoot =
2945                 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
2946         if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
2947             setDoNotAskCredentialsOnBoot();
2948         }
2949
2950         // Don't do this with the lock held, because it is going to call
2951         // back in to the service.
2952         long ident = Binder.clearCallingIdentity();
2953         try {
2954             LockPatternUtils utils = new LockPatternUtils(mContext);
2955             if (!TextUtils.isEmpty(password)) {
2956                 utils.saveLockPassword(password, null, quality, userHandle);
2957             } else {
2958                 utils.clearLock(userHandle);
2959             }
2960             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
2961             if (requireEntry) {
2962                 utils.requireCredentialEntry(UserHandle.USER_ALL);
2963             }
2964             synchronized (this) {
2965                 int newOwner = requireEntry ? callingUid : -1;
2966                 if (policy.mPasswordOwner != newOwner) {
2967                     policy.mPasswordOwner = newOwner;
2968                     saveSettingsLocked(userHandle);
2969                 }
2970             }
2971         } finally {
2972             Binder.restoreCallingIdentity(ident);
2973         }
2974
2975         return true;
2976     }
2977
2978     private void setDoNotAskCredentialsOnBoot() {
2979         synchronized (this) {
2980             DevicePolicyData policyData = getUserData(UserHandle.USER_OWNER);
2981             if (!policyData.doNotAskCredentialsOnBoot) {
2982                 policyData.doNotAskCredentialsOnBoot = true;
2983                 saveSettingsLocked(UserHandle.USER_OWNER);
2984             }
2985         }
2986     }
2987
2988     @Override
2989     public boolean getDoNotAskCredentialsOnBoot() {
2990         mContext.enforceCallingOrSelfPermission(
2991                 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
2992         synchronized (this) {
2993             DevicePolicyData policyData = getUserData(UserHandle.USER_OWNER);
2994             return policyData.doNotAskCredentialsOnBoot;
2995         }
2996     }
2997
2998     @Override
2999     public void setMaximumTimeToLock(ComponentName who, long timeMs) {
3000         if (!mHasFeature) {
3001             return;
3002         }
3003         Preconditions.checkNotNull(who, "ComponentName is null");
3004         final int userHandle = UserHandle.getCallingUserId();
3005         synchronized (this) {
3006             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3007                     DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
3008             if (ap.maximumTimeToUnlock != timeMs) {
3009                 ap.maximumTimeToUnlock = timeMs;
3010                 saveSettingsLocked(userHandle);
3011                 updateMaximumTimeToLockLocked(getUserData(userHandle));
3012             }
3013         }
3014     }
3015
3016     void updateMaximumTimeToLockLocked(DevicePolicyData policy) {
3017         long timeMs = getMaximumTimeToLock(null, policy.mUserHandle);
3018         if (policy.mLastMaximumTimeToLock == timeMs) {
3019             return;
3020         }
3021
3022         long ident = Binder.clearCallingIdentity();
3023         try {
3024             if (timeMs <= 0) {
3025                 timeMs = Integer.MAX_VALUE;
3026             } else {
3027                 // Make sure KEEP_SCREEN_ON is disabled, since that
3028                 // would allow bypassing of the maximum time to lock.
3029                 Settings.Global.putInt(mContext.getContentResolver(),
3030                         Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
3031             }
3032
3033             policy.mLastMaximumTimeToLock = timeMs;
3034             mPowerManagerInternal.setMaximumScreenOffTimeoutFromDeviceAdmin((int)timeMs);
3035         } finally {
3036             Binder.restoreCallingIdentity(ident);
3037         }
3038     }
3039
3040     @Override
3041     public long getMaximumTimeToLock(ComponentName who, int userHandle) {
3042         if (!mHasFeature) {
3043             return 0;
3044         }
3045         enforceCrossUserPermission(userHandle);
3046         synchronized (this) {
3047             long time = 0;
3048
3049             if (who != null) {
3050                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3051                 return admin != null ? admin.maximumTimeToUnlock : time;
3052             }
3053
3054             // Return strictest policy for this user and profiles that are visible from this user.
3055             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3056             for (UserInfo userInfo : profiles) {
3057                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
3058                 final int N = policy.mAdminList.size();
3059                 for (int i=0; i<N; i++) {
3060                     ActiveAdmin admin = policy.mAdminList.get(i);
3061                     if (time == 0) {
3062                         time = admin.maximumTimeToUnlock;
3063                     } else if (admin.maximumTimeToUnlock != 0
3064                             && time > admin.maximumTimeToUnlock) {
3065                         time = admin.maximumTimeToUnlock;
3066                     }
3067                 }
3068             }
3069             return time;
3070         }
3071     }
3072
3073     @Override
3074     public void lockNow() {
3075         if (!mHasFeature) {
3076             return;
3077         }
3078         synchronized (this) {
3079             // This API can only be called by an active device admin,
3080             // so try to retrieve it to check that the caller is one.
3081             getActiveAdminForCallerLocked(null,
3082                     DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
3083             lockNowUnchecked();
3084         }
3085     }
3086
3087     private void lockNowUnchecked() {
3088         long ident = Binder.clearCallingIdentity();
3089         try {
3090             // Power off the display
3091             mPowerManager.goToSleep(SystemClock.uptimeMillis(),
3092                     PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
3093             // Ensure the device is locked
3094             new LockPatternUtils(mContext).requireCredentialEntry(UserHandle.USER_ALL);
3095             getWindowManager().lockNow(null);
3096         } catch (RemoteException e) {
3097         } finally {
3098             Binder.restoreCallingIdentity(ident);
3099         }
3100     }
3101
3102     private boolean isExtStorageEncrypted() {
3103         String state = SystemProperties.get("vold.decrypt");
3104         return !"".equals(state);
3105     }
3106
3107     @Override
3108     public void enforceCanManageCaCerts(ComponentName who) {
3109         if (who == null) {
3110             if (!isCallerDelegatedCertInstaller()) {
3111                 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
3112             }
3113         } else {
3114             synchronized (this) {
3115                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3116             }
3117         }
3118     }
3119
3120     private boolean isCallerDelegatedCertInstaller() {
3121         final int callingUid = Binder.getCallingUid();
3122         final int userHandle = UserHandle.getUserId(callingUid);
3123         synchronized (this) {
3124             final DevicePolicyData policy = getUserData(userHandle);
3125             if (policy.mDelegatedCertInstallerPackage == null) {
3126                 return false;
3127             }
3128
3129             try {
3130                 int uid = mContext.getPackageManager().getPackageUid(
3131                         policy.mDelegatedCertInstallerPackage, userHandle);
3132                 return uid == callingUid;
3133             } catch (NameNotFoundException e) {
3134                 return false;
3135             }
3136         }
3137     }
3138
3139     @Override
3140     public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
3141         enforceCanManageCaCerts(admin);
3142
3143         byte[] pemCert;
3144         try {
3145             X509Certificate cert = parseCert(certBuffer);
3146             pemCert = Credentials.convertToPem(cert);
3147         } catch (CertificateException ce) {
3148             Log.e(LOG_TAG, "Problem converting cert", ce);
3149             return false;
3150         } catch (IOException ioe) {
3151             Log.e(LOG_TAG, "Problem reading cert", ioe);
3152             return false;
3153         }
3154
3155         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3156         final long id = Binder.clearCallingIdentity();
3157         try {
3158             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
3159             try {
3160                 keyChainConnection.getService().installCaCertificate(pemCert);
3161                 return true;
3162             } catch (RemoteException e) {
3163                 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
3164             } finally {
3165                 keyChainConnection.close();
3166             }
3167         } catch (InterruptedException e1) {
3168             Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
3169             Thread.currentThread().interrupt();
3170         } finally {
3171             Binder.restoreCallingIdentity(id);
3172         }
3173         return false;
3174     }
3175
3176     private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
3177         CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
3178         return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
3179                 certBuffer));
3180     }
3181
3182     @Override
3183     public void uninstallCaCerts(ComponentName admin, String[] aliases) {
3184         enforceCanManageCaCerts(admin);
3185
3186         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3187         final long id = Binder.clearCallingIdentity();
3188         try {
3189             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
3190             try {
3191                 for (int i = 0 ; i < aliases.length; i++) {
3192                     keyChainConnection.getService().deleteCaCertificate(aliases[i]);
3193                 }
3194             } catch (RemoteException e) {
3195                 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
3196             } finally {
3197                 keyChainConnection.close();
3198             }
3199         } catch (InterruptedException ie) {
3200             Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
3201             Thread.currentThread().interrupt();
3202         } finally {
3203             Binder.restoreCallingIdentity(id);
3204         }
3205     }
3206
3207     @Override
3208     public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, String alias) {
3209         if (who == null) {
3210             if (!isCallerDelegatedCertInstaller()) {
3211                 throw new SecurityException("who == null, but caller is not cert installer");
3212             }
3213         } else {
3214             synchronized (this) {
3215                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3216             }
3217         }
3218         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3219         final long id = Binder.clearCallingIdentity();
3220         try {
3221           final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
3222           try {
3223               IKeyChainService keyChain = keyChainConnection.getService();
3224               return keyChain.installKeyPair(privKey, cert, alias);
3225           } catch (RemoteException e) {
3226               Log.e(LOG_TAG, "Installing certificate", e);
3227           } finally {
3228               keyChainConnection.close();
3229           }
3230         } catch (InterruptedException e) {
3231             Log.w(LOG_TAG, "Interrupted while installing certificate", e);
3232             Thread.currentThread().interrupt();
3233         } finally {
3234             Binder.restoreCallingIdentity(id);
3235         }
3236         return false;
3237     }
3238
3239     @Override
3240     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
3241             final IBinder response) {
3242         // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
3243         if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
3244             return;
3245         }
3246
3247         final UserHandle caller = Binder.getCallingUserHandle();
3248         // If there is a profile owner, redirect to that; otherwise query the device owner.
3249         ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
3250         if (aliasChooser == null && caller.isOwner()) {
3251             ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdmin();
3252             if (deviceOwnerAdmin != null) {
3253                 aliasChooser = deviceOwnerAdmin.info.getComponent();
3254             }
3255         }
3256         if (aliasChooser == null) {
3257             sendPrivateKeyAliasResponse(null, response);
3258             return;
3259         }
3260
3261         Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
3262         intent.setComponent(aliasChooser);
3263         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
3264         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
3265         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
3266         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
3267
3268         final long id = Binder.clearCallingIdentity();
3269         try {
3270             mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
3271                 @Override
3272                 public void onReceive(Context context, Intent intent) {
3273                     final String chosenAlias = getResultData();
3274                     sendPrivateKeyAliasResponse(chosenAlias, response);
3275                 }
3276             }, null, Activity.RESULT_OK, null, null);
3277         } finally {
3278             Binder.restoreCallingIdentity(id);
3279         }
3280     }
3281
3282     private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
3283         final IKeyChainAliasCallback keyChainAliasResponse =
3284                 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
3285         new AsyncTask<Void, Void, Void>() {
3286             @Override
3287             protected Void doInBackground(Void... unused) {
3288                 try {
3289                     keyChainAliasResponse.alias(alias);
3290                 } catch (Exception e) {
3291                     // Catch everything (not just RemoteException): caller could throw a
3292                     // RuntimeException back across processes.
3293                     Log.e(LOG_TAG, "error while responding to callback", e);
3294                 }
3295                 return null;
3296             }
3297         }.execute();
3298     }
3299
3300     @Override
3301     public void setCertInstallerPackage(ComponentName who, String installerPackage)
3302             throws SecurityException {
3303         int userHandle = UserHandle.getCallingUserId();
3304         synchronized (this) {
3305             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3306             DevicePolicyData policy = getUserData(userHandle);
3307             policy.mDelegatedCertInstallerPackage = installerPackage;
3308             saveSettingsLocked(userHandle);
3309         }
3310     }
3311
3312     @Override
3313     public String getCertInstallerPackage(ComponentName who) throws SecurityException {
3314         int userHandle = UserHandle.getCallingUserId();
3315         synchronized (this) {
3316             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3317             DevicePolicyData policy = getUserData(userHandle);
3318             return policy.mDelegatedCertInstallerPackage;
3319         }
3320     }
3321
3322     private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
3323         if (wipeExtRequested) {
3324             StorageManager sm = (StorageManager) mContext.getSystemService(
3325                     Context.STORAGE_SERVICE);
3326             sm.wipeAdoptableDisks();
3327         }
3328         try {
3329             RecoverySystem.rebootWipeUserData(mContext, reason);
3330         } catch (IOException | SecurityException e) {
3331             Slog.w(LOG_TAG, "Failed requesting data wipe", e);
3332         }
3333     }
3334
3335     @Override
3336     public void wipeData(int flags, final int userHandle) {
3337         if (!mHasFeature) {
3338             return;
3339         }
3340         enforceCrossUserPermission(userHandle);
3341         final String source;
3342         synchronized (this) {
3343             // This API can only be called by an active device admin,
3344             // so try to retrieve it to check that the caller is one.
3345             final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
3346                     DeviceAdminInfo.USES_POLICY_WIPE_DATA);
3347
3348             final ComponentName cname = admin.info.getComponent();
3349             if (cname != null) {
3350                 source = cname.flattenToShortString();
3351             } else {
3352                 source = admin.info.getPackageName();
3353             }
3354
3355             long ident = Binder.clearCallingIdentity();
3356             try {
3357                 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
3358                     boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName())
3359                             && !hasUserSetupCompleted(userHandle);
3360                     if (userHandle != UserHandle.USER_OWNER
3361                             || !(isDeviceOwner(admin.info.getPackageName())
3362                                     || ownsInitialization)) {
3363                         throw new SecurityException(
3364                                "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
3365                     }
3366                     PersistentDataBlockManager manager = (PersistentDataBlockManager)
3367                             mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
3368                     if (manager != null) {
3369                         manager.wipe();
3370                     }
3371                 }
3372             } finally {
3373                 Binder.restoreCallingIdentity(ident);
3374             }
3375         }
3376         boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
3377         wipeDeviceNoLock(wipeExtRequested, userHandle,
3378                 "DevicePolicyManager.wipeData() from " + source);
3379     }
3380
3381     private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
3382         long ident = Binder.clearCallingIdentity();
3383         try {
3384             if (userHandle == UserHandle.USER_OWNER) {
3385                 wipeDataNoLock(wipeExtRequested, reason);
3386             } else {
3387                 mHandler.post(new Runnable() {
3388                     @Override
3389                     public void run() {
3390                         try {
3391                             IActivityManager am = ActivityManagerNative.getDefault();
3392                             if (am.getCurrentUser().id == userHandle) {
3393                                 am.switchUser(UserHandle.USER_OWNER);
3394                             }
3395
3396                             boolean isManagedProfile = isManagedProfile(userHandle);
3397                             if (!mUserManager.removeUser(userHandle)) {
3398                                 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
3399                             } else if (isManagedProfile) {
3400                                 sendWipeProfileNotification();
3401                             }
3402                         } catch (RemoteException re) {
3403                             // Shouldn't happen
3404                         }
3405                     }
3406                 });
3407             }
3408         } finally {
3409             Binder.restoreCallingIdentity(ident);
3410         }
3411     }
3412
3413     private void sendWipeProfileNotification() {
3414         String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
3415         Notification notification = new Notification.Builder(mContext)
3416                 .setSmallIcon(android.R.drawable.stat_sys_warning)
3417                 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
3418                 .setContentText(contentText)
3419                 .setColor(mContext.getColor(R.color.system_notification_accent_color))
3420                 .setStyle(new Notification.BigTextStyle().bigText(contentText))
3421                 .build();
3422         getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
3423     }
3424
3425     private void clearWipeProfileNotification() {
3426         getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
3427     }
3428
3429     @Override
3430     public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
3431         if (!mHasFeature) {
3432             return;
3433         }
3434         enforceCrossUserPermission(userHandle);
3435         mContext.enforceCallingOrSelfPermission(
3436                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3437
3438         synchronized (this) {
3439             ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
3440             if (admin == null) {
3441                 try {
3442                     result.sendResult(null);
3443                 } catch (RemoteException e) {
3444                 }
3445                 return;
3446             }
3447             Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
3448             intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3449             intent.setComponent(admin.info.getComponent());
3450             mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
3451                     null, new BroadcastReceiver() {
3452                 @Override
3453                 public void onReceive(Context context, Intent intent) {
3454                     try {
3455                         result.sendResult(getResultExtras(false));
3456                     } catch (RemoteException e) {
3457                     }
3458                 }
3459             }, null, Activity.RESULT_OK, null, null);
3460         }
3461     }
3462
3463     @Override
3464     public void setActivePasswordState(int quality, int length, int letters, int uppercase,
3465             int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
3466         if (!mHasFeature) {
3467             return;
3468         }
3469         enforceCrossUserPermission(userHandle);
3470         enforceNotManagedProfile(userHandle, "set the active password");
3471
3472         mContext.enforceCallingOrSelfPermission(
3473                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3474         DevicePolicyData p = getUserData(userHandle);
3475
3476         validateQualityConstant(quality);
3477
3478         synchronized (this) {
3479             if (p.mActivePasswordQuality != quality || p.mActivePasswordLength != length
3480                     || p.mFailedPasswordAttempts != 0 || p.mActivePasswordLetters != letters
3481                     || p.mActivePasswordUpperCase != uppercase
3482                     || p.mActivePasswordLowerCase != lowercase
3483                     || p.mActivePasswordNumeric != numbers
3484                     || p.mActivePasswordSymbols != symbols
3485                     || p.mActivePasswordNonLetter != nonletter) {
3486                 long ident = Binder.clearCallingIdentity();
3487                 try {
3488                     p.mActivePasswordQuality = quality;
3489                     p.mActivePasswordLength = length;
3490                     p.mActivePasswordLetters = letters;
3491                     p.mActivePasswordLowerCase = lowercase;
3492                     p.mActivePasswordUpperCase = uppercase;
3493                     p.mActivePasswordNumeric = numbers;
3494                     p.mActivePasswordSymbols = symbols;
3495                     p.mActivePasswordNonLetter = nonletter;
3496                     p.mFailedPasswordAttempts = 0;
3497                     saveSettingsLocked(userHandle);
3498                     updatePasswordExpirationsLocked(userHandle);
3499                     setExpirationAlarmCheckLocked(mContext, p);
3500                     sendAdminCommandToSelfAndProfilesLocked(
3501                             DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
3502                             DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
3503                 } finally {
3504                     Binder.restoreCallingIdentity(ident);
3505                 }
3506             }
3507         }
3508     }
3509
3510     /**
3511      * Called any time the device password is updated. Resets all password expiration clocks.
3512      */
3513     private void updatePasswordExpirationsLocked(int userHandle) {
3514             List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3515             for (UserInfo userInfo : profiles) {
3516                 int profileId = userInfo.id;
3517                 DevicePolicyData policy = getUserDataUnchecked(profileId);
3518                 final int N = policy.mAdminList.size();
3519                 if (N > 0) {
3520                     for (int i=0; i<N; i++) {
3521                         ActiveAdmin admin = policy.mAdminList.get(i);
3522                         if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
3523                             long timeout = admin.passwordExpirationTimeout;
3524                             long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3525                             admin.passwordExpirationDate = expiration;
3526                         }
3527                     }
3528                 }
3529                 saveSettingsLocked(profileId);
3530             }
3531     }
3532
3533     @Override
3534     public void reportFailedPasswordAttempt(int userHandle) {
3535         enforceCrossUserPermission(userHandle);
3536         enforceNotManagedProfile(userHandle, "report failed password attempt");
3537         mContext.enforceCallingOrSelfPermission(
3538                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3539
3540         long ident = Binder.clearCallingIdentity();
3541         try {
3542             boolean wipeData = false;
3543             int identifier = 0;
3544             synchronized (this) {
3545                 DevicePolicyData policy = getUserData(userHandle);
3546                 policy.mFailedPasswordAttempts++;
3547                 saveSettingsLocked(userHandle);
3548                 if (mHasFeature) {
3549                     ActiveAdmin strictestAdmin =
3550                             getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
3551                     int max = strictestAdmin != null
3552                             ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
3553                     if (max > 0 && policy.mFailedPasswordAttempts >= max) {
3554                         // Wipe the user/profile associated with the policy that was violated. This
3555                         // is not necessarily calling user: if the policy that fired was from a
3556                         // managed profile rather than the main user profile, we wipe former only.
3557                         wipeData = true;
3558                         identifier = strictestAdmin.getUserHandle().getIdentifier();
3559                     }
3560                     sendAdminCommandToSelfAndProfilesLocked(
3561                             DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
3562                             DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3563                 }
3564             }
3565             if (wipeData) {
3566                 // Call without holding lock.
3567                 wipeDeviceNoLock(false, identifier,
3568                         "reportFailedPasswordAttempt()");
3569             }
3570         } finally {
3571             Binder.restoreCallingIdentity(ident);
3572         }
3573     }
3574
3575     @Override
3576     public void reportSuccessfulPasswordAttempt(int userHandle) {
3577         enforceCrossUserPermission(userHandle);
3578         mContext.enforceCallingOrSelfPermission(
3579                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3580
3581         synchronized (this) {
3582             DevicePolicyData policy = getUserData(userHandle);
3583             if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
3584                 long ident = Binder.clearCallingIdentity();
3585                 try {
3586                     policy.mFailedPasswordAttempts = 0;
3587                     policy.mPasswordOwner = -1;
3588                     saveSettingsLocked(userHandle);
3589                     if (mHasFeature) {
3590                         sendAdminCommandToSelfAndProfilesLocked(
3591                                 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
3592                                 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3593                     }
3594                 } finally {
3595                     Binder.restoreCallingIdentity(ident);
3596                 }
3597             }
3598         }
3599     }
3600
3601     @Override
3602     public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
3603             String exclusionList) {
3604         if (!mHasFeature) {
3605             return null;
3606         }
3607         synchronized(this) {
3608             Preconditions.checkNotNull(who, "ComponentName is null");
3609
3610             // Only check if owner has set global proxy. We don't allow other users to set it.
3611             DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3612             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3613                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
3614
3615             // Scan through active admins and find if anyone has already
3616             // set the global proxy.
3617             Set<ComponentName> compSet = policy.mAdminMap.keySet();
3618             for (ComponentName component : compSet) {
3619                 ActiveAdmin ap = policy.mAdminMap.get(component);
3620                 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
3621                     // Another admin already sets the global proxy
3622                     // Return it to the caller.
3623                     return component;
3624                 }
3625             }
3626
3627             // If the user is not the owner, don't set the global proxy. Fail silently.
3628             if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3629                 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
3630                         + UserHandle.getCallingUserId() + " is not permitted.");
3631                 return null;
3632             }
3633             if (proxySpec == null) {
3634                 admin.specifiesGlobalProxy = false;
3635                 admin.globalProxySpec = null;
3636                 admin.globalProxyExclusionList = null;
3637             } else {
3638
3639                 admin.specifiesGlobalProxy = true;
3640                 admin.globalProxySpec = proxySpec;
3641                 admin.globalProxyExclusionList = exclusionList;
3642             }
3643
3644             // Reset the global proxy accordingly
3645             // Do this using system permissions, as apps cannot write to secure settings
3646             long origId = Binder.clearCallingIdentity();
3647             try {
3648                 resetGlobalProxyLocked(policy);
3649             } finally {
3650                 Binder.restoreCallingIdentity(origId);
3651             }
3652             return null;
3653         }
3654     }
3655
3656     @Override
3657     public ComponentName getGlobalProxyAdmin(int userHandle) {
3658         if (!mHasFeature) {
3659             return null;
3660         }
3661         enforceCrossUserPermission(userHandle);
3662         synchronized(this) {
3663             DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3664             // Scan through active admins and find if anyone has already
3665             // set the global proxy.
3666             final int N = policy.mAdminList.size();
3667             for (int i = 0; i < N; i++) {
3668                 ActiveAdmin ap = policy.mAdminList.get(i);
3669                 if (ap.specifiesGlobalProxy) {
3670                     // Device admin sets the global proxy
3671                     // Return it to the caller.
3672                     return ap.info.getComponent();
3673                 }
3674             }
3675         }
3676         // No device admin sets the global proxy.
3677         return null;
3678     }
3679
3680     @Override
3681     public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
3682         synchronized (this) {
3683             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3684         }
3685         long token = Binder.clearCallingIdentity();
3686         try {
3687             ConnectivityManager connectivityManager = (ConnectivityManager)
3688                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
3689             connectivityManager.setGlobalProxy(proxyInfo);
3690         } finally {
3691             Binder.restoreCallingIdentity(token);
3692         }
3693     }
3694
3695     private void resetGlobalProxyLocked(DevicePolicyData policy) {
3696         final int N = policy.mAdminList.size();
3697         for (int i = 0; i < N; i++) {
3698             ActiveAdmin ap = policy.mAdminList.get(i);
3699             if (ap.specifiesGlobalProxy) {
3700                 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
3701                 return;
3702             }
3703         }
3704         // No device admins defining global proxies - reset global proxy settings to none
3705         saveGlobalProxyLocked(null, null);
3706     }
3707
3708     private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
3709         if (exclusionList == null) {
3710             exclusionList = "";
3711         }
3712         if (proxySpec == null) {
3713             proxySpec = "";
3714         }
3715         // Remove white spaces
3716         proxySpec = proxySpec.trim();
3717         String data[] = proxySpec.split(":");
3718         int proxyPort = 8080;
3719         if (data.length > 1) {
3720             try {
3721                 proxyPort = Integer.parseInt(data[1]);
3722             } catch (NumberFormatException e) {}
3723         }
3724         exclusionList = exclusionList.trim();
3725         ContentResolver res = mContext.getContentResolver();
3726
3727         ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
3728         if (!proxyProperties.isValid()) {
3729             Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
3730             return;
3731         }
3732         Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
3733         Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
3734         Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3735                 exclusionList);
3736     }
3737
3738     /**
3739      * Set the storage encryption request for a single admin.  Returns the new total request
3740      * status (for all admins).
3741      */
3742     @Override
3743     public int setStorageEncryption(ComponentName who, boolean encrypt) {
3744         if (!mHasFeature) {
3745             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3746         }
3747         Preconditions.checkNotNull(who, "ComponentName is null");
3748         final int userHandle = UserHandle.getCallingUserId();
3749         synchronized (this) {
3750             // Check for permissions
3751             // Only owner can set storage encryption
3752             if (userHandle != UserHandle.USER_OWNER
3753                     || UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3754                 Slog.w(LOG_TAG, "Only owner is allowed to set storage encryption. User "
3755                         + UserHandle.getCallingUserId() + " is not permitted.");
3756                 return 0;
3757             }
3758
3759             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3760                     DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
3761
3762             // Quick exit:  If the filesystem does not support encryption, we can exit early.
3763             if (!isEncryptionSupported()) {
3764                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3765             }
3766
3767             // (1) Record the value for the admin so it's sticky
3768             if (ap.encryptionRequested != encrypt) {
3769                 ap.encryptionRequested = encrypt;
3770                 saveSettingsLocked(userHandle);
3771             }
3772
3773             DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3774             // (2) Compute "max" for all admins
3775             boolean newRequested = false;
3776             final int N = policy.mAdminList.size();
3777             for (int i = 0; i < N; i++) {
3778                 newRequested |= policy.mAdminList.get(i).encryptionRequested;
3779             }
3780
3781             // Notify OS of new request
3782             setEncryptionRequested(newRequested);
3783
3784             // Return the new global request status
3785             return newRequested
3786                     ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3787                     : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3788         }
3789     }
3790
3791     /**
3792      * Get the current storage encryption request status for a given admin, or aggregate of all
3793      * active admins.
3794      */
3795     @Override
3796     public boolean getStorageEncryption(ComponentName who, int userHandle) {
3797         if (!mHasFeature) {
3798             return false;
3799         }
3800         enforceCrossUserPermission(userHandle);
3801         synchronized (this) {
3802             // Check for permissions if a particular caller is specified
3803             if (who != null) {
3804                 // When checking for a single caller, status is based on caller's request
3805                 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
3806                 return ap != null ? ap.encryptionRequested : false;
3807             }
3808
3809             // If no particular caller is specified, return the aggregate set of requests.
3810             // This is short circuited by returning true on the first hit.
3811             DevicePolicyData policy = getUserData(userHandle);
3812             final int N = policy.mAdminList.size();
3813             for (int i = 0; i < N; i++) {
3814                 if (policy.mAdminList.get(i).encryptionRequested) {
3815                     return true;
3816                 }
3817             }
3818             return false;
3819         }
3820     }
3821
3822     /**
3823      * Get the current encryption status of the device.
3824      */
3825     @Override
3826     public int getStorageEncryptionStatus(int userHandle) {
3827         if (!mHasFeature) {
3828             // Ok to return current status.
3829         }
3830         enforceCrossUserPermission(userHandle);
3831         return getEncryptionStatus();
3832     }
3833
3834     /**
3835      * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
3836      */
3837     private boolean isEncryptionSupported() {
3838         // Note, this can be implemented as
3839         //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3840         // But is provided as a separate internal method if there's a faster way to do a
3841         // simple check for supported-or-not.
3842         return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3843     }
3844
3845     /**
3846      * Hook to low-levels:  Reporting the current status of encryption.
3847      * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
3848      * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
3849      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, or
3850      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
3851      */
3852     private int getEncryptionStatus() {
3853         String status = SystemProperties.get("ro.crypto.state", "unsupported");
3854         if ("encrypted".equalsIgnoreCase(status)) {
3855             final long token = Binder.clearCallingIdentity();
3856             try {
3857                 return LockPatternUtils.isDeviceEncrypted()
3858                         ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3859                         : DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
3860             } finally {
3861                 Binder.restoreCallingIdentity(token);
3862             }
3863         } else if ("unencrypted".equalsIgnoreCase(status)) {
3864             return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3865         } else {
3866             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3867         }
3868     }
3869
3870     /**
3871      * Hook to low-levels:  If needed, record the new admin setting for encryption.
3872      */
3873     private void setEncryptionRequested(boolean encrypt) {
3874     }
3875
3876
3877     /**
3878      * Set whether the screen capture is disabled for the user managed by the specified admin.
3879      */
3880     @Override
3881     public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
3882         if (!mHasFeature) {
3883             return;
3884         }
3885         Preconditions.checkNotNull(who, "ComponentName is null");
3886         final int userHandle = UserHandle.getCallingUserId();
3887         synchronized (this) {
3888             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3889                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3890             if (ap.disableScreenCapture != disabled) {
3891                 ap.disableScreenCapture = disabled;
3892                 saveSettingsLocked(userHandle);
3893                 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
3894             }
3895         }
3896     }
3897
3898     /**
3899      * Returns whether or not screen capture is disabled for a given admin, or disabled for any
3900      * active admin (if given admin is null).
3901      */
3902     @Override
3903     public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
3904         if (!mHasFeature) {
3905             return false;
3906         }
3907         synchronized (this) {
3908             if (who != null) {
3909                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3910                 return (admin != null) ? admin.disableScreenCapture : false;
3911             }
3912
3913             DevicePolicyData policy = getUserData(userHandle);
3914             final int N = policy.mAdminList.size();
3915             for (int i = 0; i < N; i++) {
3916                 ActiveAdmin admin = policy.mAdminList.get(i);
3917                 if (admin.disableScreenCapture) {
3918                     return true;
3919                 }
3920             }
3921             return false;
3922         }
3923     }
3924
3925     private void updateScreenCaptureDisabledInWindowManager(int userHandle, boolean disabled) {
3926         long ident = Binder.clearCallingIdentity();
3927         try {
3928             getWindowManager().setScreenCaptureDisabled(userHandle, disabled);
3929         } catch (RemoteException e) {
3930             Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
3931         } finally {
3932             Binder.restoreCallingIdentity(ident);
3933         }
3934     }
3935
3936     /**
3937      * Set whether auto time is required by the specified admin (must be device owner).
3938      */
3939     @Override
3940     public void setAutoTimeRequired(ComponentName who, boolean required) {
3941         if (!mHasFeature) {
3942             return;
3943         }
3944         Preconditions.checkNotNull(who, "ComponentName is null");
3945         final int userHandle = UserHandle.getCallingUserId();
3946         synchronized (this) {
3947             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3948                     DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3949             if (admin.requireAutoTime != required) {
3950                 admin.requireAutoTime = required;
3951                 saveSettingsLocked(userHandle);
3952             }
3953         }
3954
3955         // Turn AUTO_TIME on in settings if it is required
3956         if (required) {
3957             long ident = Binder.clearCallingIdentity();
3958             try {
3959                 Settings.Global.putInt(mContext.getContentResolver(),
3960                         Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
3961             } finally {
3962                 Binder.restoreCallingIdentity(ident);
3963             }
3964         }
3965     }
3966
3967     /**
3968      * Returns whether or not auto time is required by the device owner.
3969      */
3970     @Override
3971     public boolean getAutoTimeRequired() {
3972         if (!mHasFeature) {
3973             return false;
3974         }
3975         synchronized (this) {
3976             ActiveAdmin deviceOwner = getDeviceOwnerAdmin();
3977             return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
3978         }
3979     }
3980
3981     /**
3982      * The system property used to share the state of the camera. The native camera service
3983      * is expected to read this property and act accordingly. The userId should be appended
3984      * to this key.
3985      */
3986     public static final String SYSTEM_PROP_DISABLE_CAMERA_PREFIX = "sys.secpolicy.camera.off_";
3987
3988     /**
3989      * Disables all device cameras according to the specified admin.
3990      */
3991     @Override
3992     public void setCameraDisabled(ComponentName who, boolean disabled) {
3993         if (!mHasFeature) {
3994             return;
3995         }
3996         Preconditions.checkNotNull(who, "ComponentName is null");
3997         final int userHandle = UserHandle.getCallingUserId();
3998         synchronized (this) {
3999             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4000                     DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
4001             if (ap.disableCamera != disabled) {
4002                 ap.disableCamera = disabled;
4003                 saveSettingsLocked(userHandle);
4004             }
4005             syncDeviceCapabilitiesLocked(getUserData(userHandle));
4006         }
4007     }
4008
4009     /**
4010      * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
4011      * active admins.
4012      */
4013     @Override
4014     public boolean getCameraDisabled(ComponentName who, int userHandle) {
4015         if (!mHasFeature) {
4016             return false;
4017         }
4018         synchronized (this) {
4019             if (who != null) {
4020                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4021                 return (admin != null) ? admin.disableCamera : false;
4022             }
4023
4024             DevicePolicyData policy = getUserData(userHandle);
4025             // Determine whether or not the device camera is disabled for any active admins.
4026             final int N = policy.mAdminList.size();
4027             for (int i = 0; i < N; i++) {
4028                 ActiveAdmin admin = policy.mAdminList.get(i);
4029                 if (admin.disableCamera) {
4030                     return true;
4031                 }
4032             }
4033             return false;
4034         }
4035     }
4036
4037     /**
4038      * Selectively disable keyguard features.
4039      */
4040     @Override
4041     public void setKeyguardDisabledFeatures(ComponentName who, int which) {
4042         if (!mHasFeature) {
4043             return;
4044         }
4045         Preconditions.checkNotNull(who, "ComponentName is null");
4046         final int userHandle = UserHandle.getCallingUserId();
4047         if (isManagedProfile(userHandle)) {
4048             which = which & PROFILE_KEYGUARD_FEATURES;
4049         }
4050         synchronized (this) {
4051             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4052                     DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
4053             if (ap.disabledKeyguardFeatures != which) {
4054                 ap.disabledKeyguardFeatures = which;
4055                 saveSettingsLocked(userHandle);
4056             }
4057             syncDeviceCapabilitiesLocked(getUserData(userHandle));
4058         }
4059     }
4060
4061     /**
4062      * Gets the disabled state for features in keyguard for the given admin,
4063      * or the aggregate of all active admins if who is null.
4064      */
4065     @Override
4066     public int getKeyguardDisabledFeatures(ComponentName who, int userHandle) {
4067         if (!mHasFeature) {
4068             return 0;
4069         }
4070         enforceCrossUserPermission(userHandle);
4071         long ident = Binder.clearCallingIdentity();
4072         try {
4073             synchronized (this) {
4074                 if (who != null) {
4075                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4076                     return (admin != null) ? admin.disabledKeyguardFeatures : 0;
4077                 }
4078
4079                 UserInfo user = mUserManager.getUserInfo(userHandle);
4080                 final List<UserInfo> profiles;
4081                 if (user.isManagedProfile()) {
4082                     // If we are being asked about a managed profile just return
4083                     // keyguard features disabled by admins in the profile.
4084                     profiles = new ArrayList<UserInfo>(1);
4085                     profiles.add(user);
4086                 } else {
4087                     // Otherwise return those set by admins in the user
4088                     // and its profiles.
4089                     profiles = mUserManager.getProfiles(userHandle);
4090                 }
4091
4092                 // Determine which keyguard features are disabled by any active admin.
4093                 int which = 0;
4094                 for (UserInfo userInfo : profiles) {
4095                     DevicePolicyData policy = getUserData(userInfo.id);
4096                     final int N = policy.mAdminList.size();
4097                     for (int i = 0; i < N; i++) {
4098                         ActiveAdmin admin = policy.mAdminList.get(i);
4099                         if (userInfo.id == userHandle || !userInfo.isManagedProfile()) {
4100                             // If we are being asked explictly about this user
4101                             // return all disabled features even if its a managed profile.
4102                             which |= admin.disabledKeyguardFeatures;
4103                         } else {
4104                             // Otherwise a managed profile is only allowed to disable
4105                             // some features on the parent user.
4106                             which |= (admin.disabledKeyguardFeatures
4107                                     & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
4108                         }
4109                     }
4110                 }
4111                 return which;
4112             }
4113         } finally {
4114             Binder.restoreCallingIdentity(ident);
4115         }
4116     }
4117
4118     @Override
4119     public boolean setDeviceOwner(String packageName, String ownerName) {
4120         if (!mHasFeature) {
4121             return false;
4122         }
4123         if (packageName == null
4124                 || !DeviceOwner.isInstalled(packageName, mContext.getPackageManager())) {
4125             throw new IllegalArgumentException("Invalid package name " + packageName
4126                     + " for device owner");
4127         }
4128         synchronized (this) {
4129             enforceCanSetDeviceOwner();
4130
4131             // Shutting down backup manager service permanently.
4132             long ident = Binder.clearCallingIdentity();
4133             try {
4134                 IBackupManager ibm = IBackupManager.Stub.asInterface(
4135                         ServiceManager.getService(Context.BACKUP_SERVICE));
4136                 ibm.setBackupServiceActive(UserHandle.USER_OWNER, false);
4137             } catch (RemoteException e) {
4138                 throw new IllegalStateException("Failed deactivating backup service.", e);
4139             } finally {
4140                 Binder.restoreCallingIdentity(ident);
4141             }
4142
4143             if (mDeviceOwner == null) {
4144                 // Device owner is not set and does not exist, set it.
4145                 mDeviceOwner = DeviceOwner.createWithDeviceOwner(packageName, ownerName);
4146             } else {
4147                 // Device owner state already exists, update it.
4148                 mDeviceOwner.setDeviceOwner(packageName, ownerName);
4149             }
4150             mDeviceOwner.writeOwnerFile();
4151             updateDeviceOwnerLocked();
4152             Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
4153
4154             ident = Binder.clearCallingIdentity();
4155             try {
4156                 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
4157             } finally {
4158                 Binder.restoreCallingIdentity(ident);
4159             }
4160             return true;
4161         }
4162     }
4163
4164     @Override
4165     public boolean isDeviceOwner(String packageName) {
4166         if (!mHasFeature) {
4167             return false;
4168         }
4169         synchronized (this) {
4170             return mDeviceOwner != null
4171                     && mDeviceOwner.hasDeviceOwner()
4172                     && mDeviceOwner.getDeviceOwnerPackageName().equals(packageName);
4173         }
4174     }
4175
4176     @Override
4177     public String getDeviceOwner() {
4178         if (!mHasFeature) {
4179             return null;
4180         }
4181         synchronized (this) {
4182             if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
4183                 return mDeviceOwner.getDeviceOwnerPackageName();
4184             }
4185         }
4186         return null;
4187     }
4188
4189     @Override
4190     public String getDeviceOwnerName() {
4191         if (!mHasFeature) {
4192             return null;
4193         }
4194         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
4195         synchronized (this) {
4196             if (mDeviceOwner == null || !mDeviceOwner.hasDeviceOwner()) {
4197                 return null;
4198             }
4199             String deviceOwnerPackage = mDeviceOwner.getDeviceOwnerPackageName();
4200             return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_OWNER);
4201         }
4202     }
4203
4204     // Returns the active device owner or null if there is no device owner.
4205     private ActiveAdmin getDeviceOwnerAdmin() {
4206         String deviceOwnerPackageName = getDeviceOwner();
4207         if (deviceOwnerPackageName == null) {
4208             return null;
4209         }
4210
4211         DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
4212         final int n = policy.mAdminList.size();
4213         for (int i = 0; i < n; i++) {
4214             ActiveAdmin admin = policy.mAdminList.get(i);
4215             if (deviceOwnerPackageName.equals(admin.info.getPackageName())) {
4216                 return admin;
4217             }
4218         }
4219         return null;
4220     }
4221
4222     @Override
4223     public void clearDeviceOwner(String packageName) {
4224         Preconditions.checkNotNull(packageName, "packageName is null");
4225         try {
4226             int uid = mContext.getPackageManager().getPackageUid(packageName, 0);
4227             if (uid != Binder.getCallingUid()) {
4228                 throw new SecurityException("Invalid packageName");
4229             }
4230         } catch (NameNotFoundException e) {
4231             throw new SecurityException(e);
4232         }
4233         if (!isDeviceOwner(packageName)) {
4234             throw new SecurityException("clearDeviceOwner can only be called by the device owner");
4235         }
4236         synchronized (this) {
4237             clearUserPoliciesLocked(new UserHandle(UserHandle.USER_OWNER));
4238             if (mDeviceOwner != null) {
4239                 mDeviceOwner.clearDeviceOwner();
4240                 mDeviceOwner.writeOwnerFile();
4241                 updateDeviceOwnerLocked();
4242             }
4243         }
4244     }
4245
4246     @Override
4247     public boolean setDeviceInitializer(ComponentName who, ComponentName initializer) {
4248         if (!mHasFeature) {
4249             return false;
4250         }
4251         if (initializer == null || !DeviceOwner.isInstalled(
4252                 initializer.getPackageName(), mContext.getPackageManager())) {
4253             throw new IllegalArgumentException("Invalid component name " + initializer
4254                     + " for device initializer");
4255         }
4256         boolean isInitializerSystemApp;
4257         try {
4258             isInitializerSystemApp = isSystemApp(AppGlobals.getPackageManager(),
4259                     initializer.getPackageName(), Binder.getCallingUserHandle().getIdentifier());
4260         } catch (RemoteException | IllegalArgumentException e) {
4261             isInitializerSystemApp = false;
4262             Slog.e(LOG_TAG, "Fail to check if device initialzer is system app.", e);
4263         }
4264         if (!isInitializerSystemApp) {
4265             throw new IllegalArgumentException("Only system app can be set as device initializer.");
4266         }
4267         synchronized (this) {
4268             enforceCanSetDeviceInitializer(who);
4269
4270             if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4271                 throw new IllegalStateException(
4272                         "Trying to set device initializer but device initializer is already set.");
4273             }
4274
4275             if (mDeviceOwner == null) {
4276                 // Device owner state does not exist, create it.
4277                 mDeviceOwner = DeviceOwner.createWithDeviceInitializer(initializer);
4278             } else {
4279                 // Device owner already exists, update it.
4280                 mDeviceOwner.setDeviceInitializer(initializer);
4281             }
4282
4283             addDeviceInitializerToLockTaskPackagesLocked(UserHandle.USER_OWNER);
4284             mDeviceOwner.writeOwnerFile();
4285             return true;
4286         }
4287     }
4288
4289     private void enforceCanSetDeviceInitializer(ComponentName who) {
4290         if (who == null) {
4291             mContext.enforceCallingOrSelfPermission(
4292                     android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
4293             if (hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4294                 throw new IllegalStateException(
4295                         "Trying to set device initializer but device is already provisioned.");
4296             }
4297         } else {
4298             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4299         }
4300     }
4301
4302     @Override
4303     public boolean isDeviceInitializer(String packageName) {
4304         if (!mHasFeature) {
4305             return false;
4306         }
4307         synchronized (this) {
4308             return mDeviceOwner != null
4309                     && mDeviceOwner.hasDeviceInitializer()
4310                     && mDeviceOwner.getDeviceInitializerPackageName().equals(packageName);
4311         }
4312     }
4313
4314     @Override
4315     public String getDeviceInitializer() {
4316         if (!mHasFeature) {
4317             return null;
4318         }
4319         synchronized (this) {
4320             if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4321                 return mDeviceOwner.getDeviceInitializerPackageName();
4322             }
4323         }
4324         return null;
4325     }
4326
4327     @Override
4328     public ComponentName getDeviceInitializerComponent() {
4329         if (!mHasFeature) {
4330             return null;
4331         }
4332         synchronized (this) {
4333             if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4334                 return mDeviceOwner.getDeviceInitializerComponent();
4335             }
4336         }
4337         return null;
4338     }
4339
4340     @Override
4341     public void clearDeviceInitializer(ComponentName who) {
4342         if (!mHasFeature) {
4343             return;
4344         }
4345         Preconditions.checkNotNull(who, "ComponentName is null");
4346
4347         ActiveAdmin admin = getActiveAdminUncheckedLocked(who, UserHandle.getCallingUserId());
4348
4349         if (admin.getUid() != Binder.getCallingUid()) {
4350             throw new SecurityException("Admin " + who + " is not owned by uid "
4351                     + Binder.getCallingUid());
4352         }
4353
4354         if (!isDeviceInitializer(admin.info.getPackageName())
4355                 && !isDeviceOwner(admin.info.getPackageName())) {
4356             throw new SecurityException(
4357                     "clearDeviceInitializer can only be called by the device initializer/owner");
4358         }
4359         synchronized (this) {
4360             long ident = Binder.clearCallingIdentity();
4361             try {
4362                 if (mDeviceOwner != null) {
4363                     mDeviceOwner.clearDeviceInitializer();
4364                     mDeviceOwner.writeOwnerFile();
4365                 }
4366             } finally {
4367                 Binder.restoreCallingIdentity(ident);
4368             }
4369         }
4370     }
4371
4372     @Override
4373     public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
4374         if (!mHasFeature) {
4375             return false;
4376         }
4377         if (who == null
4378                 || !DeviceOwner.isInstalledForUser(who.getPackageName(), userHandle)) {
4379             throw new IllegalArgumentException("Component " + who
4380                     + " not installed for userId:" + userHandle);
4381         }
4382         synchronized (this) {
4383             enforceCanSetProfileOwner(userHandle);
4384             if (mDeviceOwner == null) {
4385                 // Device owner state does not exist, create it.
4386                 mDeviceOwner = DeviceOwner.createWithProfileOwner(who, ownerName,
4387                         userHandle);
4388             } else {
4389                 // Device owner state already exists, update it.
4390                 mDeviceOwner.setProfileOwner(who, ownerName, userHandle);
4391             }
4392             mDeviceOwner.writeOwnerFile();
4393             return true;
4394         }
4395     }
4396
4397     @Override
4398     public void clearProfileOwner(ComponentName who) {
4399         if (!mHasFeature) {
4400             return;
4401         }
4402         UserHandle callingUser = Binder.getCallingUserHandle();
4403         // Check if this is the profile owner who is calling
4404         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4405         synchronized (this) {
4406             clearUserPoliciesLocked(callingUser);
4407             if (mDeviceOwner != null) {
4408                 mDeviceOwner.removeProfileOwner(callingUser.getIdentifier());
4409                 mDeviceOwner.writeOwnerFile();
4410             }
4411         }
4412     }
4413
4414     private void clearUserPoliciesLocked(UserHandle userHandle) {
4415         int userId = userHandle.getIdentifier();
4416         // Reset some of the user-specific policies
4417         DevicePolicyData policy = getUserData(userId);
4418         policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
4419         policy.mDelegatedCertInstallerPackage = null;
4420         policy.mStatusBarDisabled = false;
4421         saveSettingsLocked(userId);
4422
4423         final long ident = Binder.clearCallingIdentity();
4424         try {
4425             clearUserRestrictions(userHandle);
4426             AppGlobals.getPackageManager().updatePermissionFlagsForAllApps(
4427                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
4428                     0  /* flagValues */, userHandle.getIdentifier());
4429         } catch (RemoteException re) {
4430         } finally {
4431             Binder.restoreCallingIdentity(ident);
4432         }
4433     }
4434
4435
4436     private void clearUserRestrictions(UserHandle userHandle) {
4437         Bundle userRestrictions = mUserManager.getUserRestrictions();
4438         mUserManager.setUserRestrictions(new Bundle(), userHandle);
4439         IAudioService iAudioService = IAudioService.Stub.asInterface(
4440                 ServiceManager.getService(Context.AUDIO_SERVICE));
4441         if (userRestrictions.getBoolean(UserManager.DISALLOW_ADJUST_VOLUME)) {
4442             try {
4443                 iAudioService.setMasterMute(true, 0, mContext.getPackageName(),
4444                         userHandle.getIdentifier());
4445             } catch (RemoteException e) {
4446                 // Not much we can do here.
4447             }
4448         }
4449         if (userRestrictions.getBoolean(UserManager.DISALLOW_UNMUTE_MICROPHONE)) {
4450             try {
4451                 iAudioService.setMicrophoneMute(true, mContext.getPackageName(),
4452                         userHandle.getIdentifier());
4453             } catch (RemoteException e) {
4454                 // Not much we can do here.
4455             }
4456         }
4457     }
4458
4459     @Override
4460     public boolean hasUserSetupCompleted() {
4461         return hasUserSetupCompleted(UserHandle.getCallingUserId());
4462     }
4463
4464     private boolean hasUserSetupCompleted(int userHandle) {
4465         if (!mHasFeature) {
4466             return true;
4467         }
4468         DevicePolicyData policy = getUserData(userHandle);
4469         // If policy is null, return true, else check if the setup has completed.
4470         return policy == null || policy.mUserSetupComplete;
4471     }
4472
4473     @Override
4474     public boolean setUserEnabled(ComponentName who) {
4475         if (!mHasFeature) {
4476             return false;
4477         }
4478         synchronized (this) {
4479             if (who == null) {
4480                 throw new NullPointerException("ComponentName is null");
4481             }
4482             int userId = UserHandle.getCallingUserId();
4483
4484             ActiveAdmin activeAdmin =
4485                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4486             if (!isDeviceInitializer(activeAdmin.info.getPackageName())) {
4487                 throw new SecurityException(
4488                         "This method can only be called by device initializers");
4489             }
4490
4491             long id = Binder.clearCallingIdentity();
4492             try {
4493                 if (!isDeviceOwner(activeAdmin.info.getPackageName())) {
4494                     IPackageManager ipm = AppGlobals.getPackageManager();
4495                     ipm.setComponentEnabledSetting(who,
4496                             PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
4497                             PackageManager.DONT_KILL_APP, userId);
4498
4499                     removeActiveAdmin(who, userId);
4500                 }
4501
4502                 if (userId == UserHandle.USER_OWNER) {
4503                     Settings.Global.putInt(mContext.getContentResolver(),
4504                             Settings.Global.DEVICE_PROVISIONED, 1);
4505                 }
4506                 Settings.Secure.putIntForUser(mContext.getContentResolver(),
4507                         Settings.Secure.USER_SETUP_COMPLETE, 1, userId);
4508             } catch (RemoteException e) {
4509                 Log.i(LOG_TAG, "Can't talk to package manager", e);
4510                 return false;
4511             } finally {
4512                 restoreCallingIdentity(id);
4513             }
4514             return true;
4515         }
4516     }
4517
4518     @Override
4519     public void setProfileEnabled(ComponentName who) {
4520         if (!mHasFeature) {
4521             return;
4522         }
4523         Preconditions.checkNotNull(who, "ComponentName is null");
4524         final int userHandle = UserHandle.getCallingUserId();
4525         synchronized (this) {
4526             // Check if this is the profile owner who is calling
4527             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4528             int userId = UserHandle.getCallingUserId();
4529
4530             long id = Binder.clearCallingIdentity();
4531             try {
4532                 mUserManager.setUserEnabled(userId);
4533                 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
4534                 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle));
4535                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
4536                         Intent.FLAG_RECEIVER_FOREGROUND);
4537                 // TODO This should send to parent of profile (which is always owner at the moment).
4538                 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
4539             } finally {
4540                 restoreCallingIdentity(id);
4541             }
4542         }
4543     }
4544
4545     @Override
4546     public void setProfileName(ComponentName who, String profileName) {
4547         Preconditions.checkNotNull(who, "ComponentName is null");
4548         int userId = UserHandle.getCallingUserId();
4549         // Check if this is the profile owner (includes device owner).
4550         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4551
4552         long id = Binder.clearCallingIdentity();
4553         try {
4554             mUserManager.setUserName(userId, profileName);
4555         } finally {
4556             restoreCallingIdentity(id);
4557         }
4558     }
4559
4560     @Override
4561     public ComponentName getProfileOwner(int userHandle) {
4562         if (!mHasFeature) {
4563             return null;
4564         }
4565
4566         synchronized (this) {
4567             if (mDeviceOwner != null) {
4568                 return mDeviceOwner.getProfileOwnerComponent(userHandle);
4569             }
4570         }
4571         return null;
4572     }
4573
4574     // Returns the active profile owner for this user or null if the current user has no
4575     // profile owner.
4576     private ActiveAdmin getProfileOwnerAdmin(int userHandle) {
4577         ComponentName profileOwner =
4578                 mDeviceOwner != null ? mDeviceOwner.getProfileOwnerComponent(userHandle) : null;
4579         if (profileOwner == null) {
4580             return null;
4581         }
4582         DevicePolicyData policy = getUserData(userHandle);
4583         final int n = policy.mAdminList.size();
4584         for (int i = 0; i < n; i++) {
4585             ActiveAdmin admin = policy.mAdminList.get(i);
4586             if (profileOwner.equals(admin.info.getComponent())) {
4587                 return admin;
4588             }
4589         }
4590         return null;
4591     }
4592
4593     @Override
4594     public String getProfileOwnerName(int userHandle) {
4595         if (!mHasFeature) {
4596             return null;
4597         }
4598         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
4599         ComponentName profileOwner = getProfileOwner(userHandle);
4600         if (profileOwner == null) {
4601             return null;
4602         }
4603         return getApplicationLabel(profileOwner.getPackageName(), userHandle);
4604     }
4605
4606     /**
4607      * Canonical name for a given package.
4608      */
4609     private String getApplicationLabel(String packageName, int userHandle) {
4610         long token = Binder.clearCallingIdentity();
4611         try {
4612             final Context userContext;
4613             try {
4614                 UserHandle handle = new UserHandle(userHandle);
4615                 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
4616             } catch (PackageManager.NameNotFoundException nnfe) {
4617                 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
4618                 return null;
4619             }
4620             ApplicationInfo appInfo = userContext.getApplicationInfo();
4621             CharSequence result = null;
4622             if (appInfo != null) {
4623                 PackageManager pm = userContext.getPackageManager();
4624                 result = pm.getApplicationLabel(appInfo);
4625             }
4626             return result != null ? result.toString() : null;
4627         } finally {
4628             Binder.restoreCallingIdentity(token);
4629         }
4630     }
4631
4632     /**
4633      * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
4634      * permission.
4635      * The profile owner can only be set before the user setup phase has completed,
4636      * except for:
4637      * - SYSTEM_UID
4638      * - adb if there are not accounts.
4639      */
4640     private void enforceCanSetProfileOwner(int userHandle) {
4641         UserInfo info = mUserManager.getUserInfo(userHandle);
4642         if (info == null) {
4643             // User doesn't exist.
4644             throw new IllegalArgumentException(
4645                     "Attempted to set profile owner for invalid userId: " + userHandle);
4646         }
4647         if (info.isGuest()) {
4648             throw new IllegalStateException("Cannot set a profile owner on a guest");
4649         }
4650         if (getProfileOwner(userHandle) != null) {
4651             throw new IllegalStateException("Trying to set the profile owner, but profile owner "
4652                     + "is already set.");
4653         }
4654         int callingUid = Binder.getCallingUid();
4655         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
4656             if (hasUserSetupCompleted(userHandle) &&
4657                     AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) {
4658                 throw new IllegalStateException("Not allowed to set the profile owner because "
4659                         + "there are already some accounts on the profile");
4660             }
4661             return;
4662         }
4663         mContext.enforceCallingOrSelfPermission(
4664                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
4665         if (hasUserSetupCompleted(userHandle)
4666                 && UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
4667             throw new IllegalStateException("Cannot set the profile owner on a user which is "
4668                     + "already set-up");
4669         }
4670     }
4671
4672     /**
4673      * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
4674      * permission.
4675      * The device owner can only be set before the setup phase of the primary user has completed,
4676      * except for adb if no accounts or additional users are present on the device.
4677      */
4678     private void enforceCanSetDeviceOwner() {
4679         if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
4680             throw new IllegalStateException("Trying to set the device owner, but device owner "
4681                     + "is already set.");
4682         }
4683         int callingUid = Binder.getCallingUid();
4684         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
4685             if (!hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4686                 return;
4687             }
4688             if (mUserManager.getUserCount() > 1) {
4689                 throw new IllegalStateException("Not allowed to set the device owner because there "
4690                         + "are already several users on the device");
4691             }
4692             if (AccountManager.get(mContext).getAccounts().length > 0) {
4693                 throw new IllegalStateException("Not allowed to set the device owner because there "
4694                         + "are already some accounts on the device");
4695             }
4696             return;
4697         }
4698         mContext.enforceCallingOrSelfPermission(
4699                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
4700         if (hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4701             throw new IllegalStateException("Cannot set the device owner if the device is "
4702                     + "already set-up");
4703         }
4704     }
4705
4706     private void enforceCrossUserPermission(int userHandle) {
4707         if (userHandle < 0) {
4708             throw new IllegalArgumentException("Invalid userId " + userHandle);
4709         }
4710         final int callingUid = Binder.getCallingUid();
4711         if (userHandle == UserHandle.getUserId(callingUid)) return;
4712         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4713             mContext.enforceCallingOrSelfPermission(
4714                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have"
4715                     + " INTERACT_ACROSS_USERS_FULL permission");
4716         }
4717     }
4718
4719     private void enforceSystemProcess(String message) {
4720         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4721             throw new SecurityException(message);
4722         }
4723     }
4724
4725     private void enforceNotManagedProfile(int userHandle, String message) {
4726         if(isManagedProfile(userHandle)) {
4727             throw new SecurityException("You can not " + message + " for a managed profile. ");
4728         }
4729     }
4730
4731     private UserInfo getProfileParent(int userHandle) {
4732         long ident = Binder.clearCallingIdentity();
4733         try {
4734             return mUserManager.getProfileParent(userHandle);
4735         } finally {
4736             Binder.restoreCallingIdentity(ident);
4737         }
4738     }
4739
4740     private boolean isManagedProfile(int userHandle) {
4741         long ident = Binder.clearCallingIdentity();
4742         try {
4743             return mUserManager.getUserInfo(userHandle).isManagedProfile();
4744         } finally {
4745             Binder.restoreCallingIdentity(ident);
4746         }
4747     }
4748
4749     private void enableIfNecessary(String packageName, int userId) {
4750         try {
4751             IPackageManager ipm = AppGlobals.getPackageManager();
4752             ApplicationInfo ai = ipm.getApplicationInfo(packageName,
4753                     PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
4754                     userId);
4755             if (ai.enabledSetting
4756                     == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
4757                 ipm.setApplicationEnabledSetting(packageName,
4758                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
4759                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
4760             }
4761         } catch (RemoteException e) {
4762         }
4763     }
4764
4765     @Override
4766     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4767         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4768                 != PackageManager.PERMISSION_GRANTED) {
4769
4770             pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
4771                     + Binder.getCallingPid()
4772                     + ", uid=" + Binder.getCallingUid());
4773             return;
4774         }
4775
4776         final Printer p = new PrintWriterPrinter(pw);
4777
4778         synchronized (this) {
4779             p.println("Current Device Policy Manager state:");
4780             if (mDeviceOwner != null) {
4781                 mDeviceOwner.dump("  ", pw);
4782             }
4783             int userCount = mUserData.size();
4784             for (int u = 0; u < userCount; u++) {
4785                 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
4786                 p.println("  Enabled Device Admins (User " + policy.mUserHandle + "):");
4787                 final int N = policy.mAdminList.size();
4788                 for (int i=0; i<N; i++) {
4789                     ActiveAdmin ap = policy.mAdminList.get(i);
4790                     if (ap != null) {
4791                         pw.print("  "); pw.print(ap.info.getComponent().flattenToShortString());
4792                                 pw.println(":");
4793                         ap.dump("    ", pw);
4794                     }
4795                 }
4796                 if (!policy.mRemovingAdmins.isEmpty()) {
4797                     p.println("  Removing Device Admins (User " + policy.mUserHandle + "): "
4798                             + policy.mRemovingAdmins);
4799                 }
4800
4801                 pw.println(" ");
4802                 pw.print("  mPasswordOwner="); pw.println(policy.mPasswordOwner);
4803             }
4804         }
4805     }
4806
4807     @Override
4808     public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
4809             ComponentName activity) {
4810         Preconditions.checkNotNull(who, "ComponentName is null");
4811         final int userHandle = UserHandle.getCallingUserId();
4812         synchronized (this) {
4813             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4814
4815             IPackageManager pm = AppGlobals.getPackageManager();
4816             long id = Binder.clearCallingIdentity();
4817             try {
4818                 pm.addPersistentPreferredActivity(filter, activity, userHandle);
4819             } catch (RemoteException re) {
4820                 // Shouldn't happen
4821             } finally {
4822                 restoreCallingIdentity(id);
4823             }
4824         }
4825     }
4826
4827     @Override
4828     public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
4829         Preconditions.checkNotNull(who, "ComponentName is null");
4830         final int userHandle = UserHandle.getCallingUserId();
4831         synchronized (this) {
4832             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4833
4834             IPackageManager pm = AppGlobals.getPackageManager();
4835             long id = Binder.clearCallingIdentity();
4836             try {
4837                 pm.clearPackagePersistentPreferredActivities(packageName, userHandle);
4838             } catch (RemoteException re) {
4839                 // Shouldn't happen
4840             } finally {
4841                 restoreCallingIdentity(id);
4842             }
4843         }
4844     }
4845
4846     @Override
4847     public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
4848         Preconditions.checkNotNull(who, "ComponentName is null");
4849         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4850         synchronized (this) {
4851             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4852
4853             long id = Binder.clearCallingIdentity();
4854             try {
4855                 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
4856             } finally {
4857                 restoreCallingIdentity(id);
4858             }
4859         }
4860     }
4861
4862     @Override
4863     public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
4864             PersistableBundle args) {
4865         if (!mHasFeature) {
4866             return;
4867         }
4868         Preconditions.checkNotNull(admin, "admin is null");
4869         Preconditions.checkNotNull(agent, "agent is null");
4870         final int userHandle = UserHandle.getCallingUserId();
4871         enforceNotManagedProfile(userHandle, "set trust agent configuration");
4872         synchronized (this) {
4873             ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
4874                     DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
4875             ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
4876             saveSettingsLocked(userHandle);
4877             syncDeviceCapabilitiesLocked(getUserData(userHandle));
4878         }
4879     }
4880
4881     @Override
4882     public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
4883             ComponentName agent, int userHandle) {
4884         if (!mHasFeature) {
4885             return null;
4886         }
4887         Preconditions.checkNotNull(agent, "agent null");
4888         enforceCrossUserPermission(userHandle);
4889
4890         synchronized (this) {
4891             final String componentName = agent.flattenToString();
4892             if (admin != null) {
4893                 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle);
4894                 if (ap == null) return null;
4895                 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
4896                 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
4897                 List<PersistableBundle> result = new ArrayList<PersistableBundle>();
4898                 result.add(trustAgentInfo.options);
4899                 return result;
4900             }
4901
4902             // Return strictest policy for this user and profiles that are visible from this user.
4903             final List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
4904             List<PersistableBundle> result = null;
4905
4906             // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
4907             // of the options. If any admin doesn't have options, discard options for the rest
4908             // and return null.
4909             boolean allAdminsHaveOptions = true;
4910             for (UserInfo userInfo : profiles) {
4911                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4912                 final int N = policy.mAdminList.size();
4913                 for (int i=0; i < N; i++) {
4914                     final ActiveAdmin active = policy.mAdminList.get(i);
4915                     final boolean disablesTrust = (active.disabledKeyguardFeatures
4916                             & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
4917                     final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
4918                     if (info != null && info.options != null && !info.options.isEmpty()) {
4919                         if (disablesTrust) {
4920                             if (result == null) {
4921                                 result = new ArrayList<PersistableBundle>();
4922                             }
4923                             result.add(info.options);
4924                         } else {
4925                             Log.w(LOG_TAG, "Ignoring admin " + active.info
4926                                     + " because it has trust options but doesn't declare "
4927                                     + "KEYGUARD_DISABLE_TRUST_AGENTS");
4928                         }
4929                     } else if (disablesTrust) {
4930                         allAdminsHaveOptions = false;
4931                         break;
4932                     }
4933                 }
4934             }
4935             return allAdminsHaveOptions ? result : null;
4936         }
4937     }
4938
4939     @Override
4940     public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
4941         Preconditions.checkNotNull(who, "ComponentName is null");
4942         synchronized (this) {
4943             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4944
4945             int userHandle = UserHandle.getCallingUserId();
4946             DevicePolicyData userData = getUserData(userHandle);
4947             userData.mRestrictionsProvider = permissionProvider;
4948             saveSettingsLocked(userHandle);
4949         }
4950     }
4951
4952     @Override
4953     public ComponentName getRestrictionsProvider(int userHandle) {
4954         synchronized (this) {
4955             if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4956                 throw new SecurityException("Only the system can query the permission provider");
4957             }
4958             DevicePolicyData userData = getUserData(userHandle);
4959             return userData != null ? userData.mRestrictionsProvider : null;
4960         }
4961     }
4962
4963     @Override
4964     public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
4965         Preconditions.checkNotNull(who, "ComponentName is null");
4966         int callingUserId = UserHandle.getCallingUserId();
4967         synchronized (this) {
4968             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4969
4970             IPackageManager pm = AppGlobals.getPackageManager();
4971             long id = Binder.clearCallingIdentity();
4972             try {
4973                 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
4974                     pm.addCrossProfileIntentFilter(filter, who.getPackageName(), callingUserId,
4975                             UserHandle.USER_OWNER, 0);
4976                 }
4977                 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
4978                     pm.addCrossProfileIntentFilter(filter, who.getPackageName(),
4979                             UserHandle.USER_OWNER, callingUserId, 0);
4980                 }
4981             } catch (RemoteException re) {
4982                 // Shouldn't happen
4983             } finally {
4984                 restoreCallingIdentity(id);
4985             }
4986         }
4987     }
4988
4989     @Override
4990     public void clearCrossProfileIntentFilters(ComponentName who) {
4991         Preconditions.checkNotNull(who, "ComponentName is null");
4992         int callingUserId = UserHandle.getCallingUserId();
4993         synchronized (this) {
4994             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4995             IPackageManager pm = AppGlobals.getPackageManager();
4996             long id = Binder.clearCallingIdentity();
4997             try {
4998                 // Removing those that go from the managed profile to the primary user.
4999                 pm.clearCrossProfileIntentFilters(callingUserId, who.getPackageName());
5000                 // And those that go from the primary user to the managed profile.
5001                 // If we want to support multiple managed profiles, we will have to only remove
5002                 // those that have callingUserId as their target.
5003                 pm.clearCrossProfileIntentFilters(UserHandle.USER_OWNER, who.getPackageName());
5004             } catch (RemoteException re) {
5005                 // Shouldn't happen
5006             } finally {
5007                 restoreCallingIdentity(id);
5008             }
5009         }
5010     }
5011
5012     /**
5013      * @return true if all packages in enabledPackages are either in the list
5014      * permittedList or are a system app.
5015      */
5016     private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
5017             List<String> permittedList) {
5018         int userIdToCheck = UserHandle.getCallingUserId();
5019         long id = Binder.clearCallingIdentity();
5020         try {
5021             // If we have an enabled packages list for a managed profile the packages
5022             // we should check are installed for the parent user.
5023             UserInfo user = mUserManager.getUserInfo(userIdToCheck);
5024             if (user.isManagedProfile()) {
5025                 userIdToCheck = user.profileGroupId;
5026             }
5027
5028             IPackageManager pm = AppGlobals.getPackageManager();
5029             for (String enabledPackage : enabledPackages) {
5030                 boolean systemService = false;
5031                 try {
5032                     ApplicationInfo applicationInfo = pm.getApplicationInfo(enabledPackage,
5033                             PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
5034                     systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5035                 } catch (RemoteException e) {
5036                     Log.i(LOG_TAG, "Can't talk to package managed", e);
5037                 }
5038                 if (!systemService && !permittedList.contains(enabledPackage)) {
5039                     return false;
5040                 }
5041             }
5042         } finally {
5043             restoreCallingIdentity(id);
5044         }
5045         return true;
5046     }
5047
5048     private AccessibilityManager getAccessibilityManagerForUser(int userId) {
5049         // Not using AccessibilityManager.getInstance because that guesses
5050         // at the user you require based on callingUid and caches for a given
5051         // process.
5052         IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
5053         IAccessibilityManager service = iBinder == null
5054                 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
5055         return new AccessibilityManager(mContext, service, userId);
5056     }
5057
5058     @Override
5059     public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
5060         if (!mHasFeature) {
5061             return false;
5062         }
5063         Preconditions.checkNotNull(who, "ComponentName is null");
5064
5065         if (packageList != null) {
5066             int userId = UserHandle.getCallingUserId();
5067             List<AccessibilityServiceInfo> enabledServices = null;
5068             long id = Binder.clearCallingIdentity();
5069             try {
5070                 UserInfo user = mUserManager.getUserInfo(userId);
5071                 if (user.isManagedProfile()) {
5072                     userId = user.profileGroupId;
5073                 }
5074                 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
5075                 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
5076                         AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
5077             } finally {
5078                 restoreCallingIdentity(id);
5079             }
5080
5081             if (enabledServices != null) {
5082                 List<String> enabledPackages = new ArrayList<String>();
5083                 for (AccessibilityServiceInfo service : enabledServices) {
5084                     enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
5085                 }
5086                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
5087                     Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
5088                             + "because it contains already enabled accesibility services.");
5089                     return false;
5090                 }
5091             }
5092         }
5093
5094         synchronized (this) {
5095             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5096                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5097             admin.permittedAccessiblityServices = packageList;
5098             saveSettingsLocked(UserHandle.getCallingUserId());
5099         }
5100         return true;
5101     }
5102
5103     @Override
5104     public List getPermittedAccessibilityServices(ComponentName who) {
5105         if (!mHasFeature) {
5106             return null;
5107         }
5108         Preconditions.checkNotNull(who, "ComponentName is null");
5109
5110         synchronized (this) {
5111             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5112                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5113             return admin.permittedAccessiblityServices;
5114         }
5115     }
5116
5117     @Override
5118     public List getPermittedAccessibilityServicesForUser(int userId) {
5119         if (!mHasFeature) {
5120             return null;
5121         }
5122         synchronized (this) {
5123             List<String> result = null;
5124             // If we have multiple profiles we return the intersection of the
5125             // permitted lists. This can happen in cases where we have a device
5126             // and profile owner.
5127             List<UserInfo> profiles = mUserManager.getProfiles(userId);
5128             final int PROFILES_SIZE = profiles.size();
5129             for (int i = 0; i < PROFILES_SIZE; ++i) {
5130                 // Just loop though all admins, only device or profiles
5131                 // owners can have permitted lists set.
5132                 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
5133                 final int N = policy.mAdminList.size();
5134                 for (int j = 0; j < N; j++) {
5135                     ActiveAdmin admin = policy.mAdminList.get(j);
5136                     List<String> fromAdmin = admin.permittedAccessiblityServices;
5137                     if (fromAdmin != null) {
5138                         if (result == null) {
5139                             result = new ArrayList<String>(fromAdmin);
5140                         } else {
5141                             result.retainAll(fromAdmin);
5142                         }
5143                     }
5144                 }
5145             }
5146
5147             // If we have a permitted list add all system accessibility services.
5148             if (result != null) {
5149                 long id = Binder.clearCallingIdentity();
5150                 try {
5151                     UserInfo user = mUserManager.getUserInfo(userId);
5152                     if (user.isManagedProfile()) {
5153                         userId = user.profileGroupId;
5154                     }
5155                     AccessibilityManager accessibilityManager =
5156                             getAccessibilityManagerForUser(userId);
5157                     List<AccessibilityServiceInfo> installedServices =
5158                             accessibilityManager.getInstalledAccessibilityServiceList();
5159
5160                     IPackageManager pm = AppGlobals.getPackageManager();
5161                     if (installedServices != null) {
5162                         for (AccessibilityServiceInfo service : installedServices) {
5163                             ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
5164                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
5165                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5166                                 result.add(serviceInfo.packageName);
5167                             }
5168                         }
5169                     }
5170                 } finally {
5171                     restoreCallingIdentity(id);
5172                 }
5173             }
5174
5175             return result;
5176         }
5177     }
5178
5179     private boolean checkCallerIsCurrentUserOrProfile() {
5180         int callingUserId = UserHandle.getCallingUserId();
5181         long token = Binder.clearCallingIdentity();
5182         try {
5183             UserInfo currentUser;
5184             UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
5185             try {
5186                 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
5187             } catch (RemoteException e) {
5188                 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
5189                 return false;
5190             }
5191
5192             if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
5193                 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
5194                         + "of a user that isn't the foreground user.");
5195                 return false;
5196             }
5197             if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
5198                 Slog.e(LOG_TAG, "Cannot set permitted input methods "
5199                         + "of a user that isn't the foreground user.");
5200                 return false;
5201             }
5202         } finally {
5203             Binder.restoreCallingIdentity(token);
5204         }
5205         return true;
5206     }
5207
5208     @Override
5209     public boolean setPermittedInputMethods(ComponentName who, List packageList) {
5210         if (!mHasFeature) {
5211             return false;
5212         }
5213         Preconditions.checkNotNull(who, "ComponentName is null");
5214
5215         // TODO When InputMethodManager supports per user calls remove
5216         //      this restriction.
5217         if (!checkCallerIsCurrentUserOrProfile()) {
5218             return false;
5219         }
5220
5221         if (packageList != null) {
5222             // InputMethodManager fetches input methods for current user.
5223             // So this can only be set when calling user is the current user
5224             // or parent is current user in case of managed profiles.
5225             InputMethodManager inputMethodManager = (InputMethodManager) mContext
5226                     .getSystemService(Context.INPUT_METHOD_SERVICE);
5227             List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
5228
5229             if (enabledImes != null) {
5230                 List<String> enabledPackages = new ArrayList<String>();
5231                 for (InputMethodInfo ime : enabledImes) {
5232                     enabledPackages.add(ime.getPackageName());
5233                 }
5234                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
5235                     Slog.e(LOG_TAG, "Cannot set permitted input methods, "
5236                             + "because it contains already enabled input method.");
5237                     return false;
5238                 }
5239             }
5240         }
5241
5242         synchronized (this) {
5243             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5244                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5245             admin.permittedInputMethods = packageList;
5246             saveSettingsLocked(UserHandle.getCallingUserId());
5247         }
5248         return true;
5249     }
5250
5251     @Override
5252     public List getPermittedInputMethods(ComponentName who) {
5253         if (!mHasFeature) {
5254             return null;
5255         }
5256         Preconditions.checkNotNull(who, "ComponentName is null");
5257
5258         synchronized (this) {
5259             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5260                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5261             return admin.permittedInputMethods;
5262         }
5263     }
5264
5265     @Override
5266     public List getPermittedInputMethodsForCurrentUser() {
5267         UserInfo currentUser;
5268         try {
5269             currentUser = ActivityManagerNative.getDefault().getCurrentUser();
5270         } catch (RemoteException e) {
5271             Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
5272             // Activity managed is dead, just allow all IMEs
5273             return null;
5274         }
5275
5276         int userId = currentUser.id;
5277         synchronized (this) {
5278             List<String> result = null;
5279             // If we have multiple profiles we return the intersection of the
5280             // permitted lists. This can happen in cases where we have a device
5281             // and profile owner.
5282             List<UserInfo> profiles = mUserManager.getProfiles(userId);
5283             final int PROFILES_SIZE = profiles.size();
5284             for (int i = 0; i < PROFILES_SIZE; ++i) {
5285                 // Just loop though all admins, only device or profiles
5286                 // owners can have permitted lists set.
5287                 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
5288                 final int N = policy.mAdminList.size();
5289                 for (int j = 0; j < N; j++) {
5290                     ActiveAdmin admin = policy.mAdminList.get(j);
5291                     List<String> fromAdmin = admin.permittedInputMethods;
5292                     if (fromAdmin != null) {
5293                         if (result == null) {
5294                             result = new ArrayList<String>(fromAdmin);
5295                         } else {
5296                             result.retainAll(fromAdmin);
5297                         }
5298                     }
5299                 }
5300             }
5301
5302             // If we have a permitted list add all system input methods.
5303             if (result != null) {
5304                 InputMethodManager inputMethodManager = (InputMethodManager) mContext
5305                         .getSystemService(Context.INPUT_METHOD_SERVICE);
5306                 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
5307                 long id = Binder.clearCallingIdentity();
5308                 try {
5309                     IPackageManager pm = AppGlobals.getPackageManager();
5310                     if (imes != null) {
5311                         for (InputMethodInfo ime : imes) {
5312                             ServiceInfo serviceInfo = ime.getServiceInfo();
5313                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
5314                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5315                                 result.add(serviceInfo.packageName);
5316                             }
5317                         }
5318                     }
5319                 } finally {
5320                     restoreCallingIdentity(id);
5321                 }
5322             }
5323             return result;
5324         }
5325     }
5326
5327     @Override
5328     public UserHandle createUser(ComponentName who, String name) {
5329         Preconditions.checkNotNull(who, "ComponentName is null");
5330         synchronized (this) {
5331             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5332
5333             long id = Binder.clearCallingIdentity();
5334             try {
5335                 UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */);
5336                 if (userInfo != null) {
5337                     return userInfo.getUserHandle();
5338                 }
5339                 return null;
5340             } finally {
5341                 restoreCallingIdentity(id);
5342             }
5343         }
5344     }
5345
5346     @Override
5347     public UserHandle createAndInitializeUser(ComponentName who, String name,
5348             String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) {
5349         UserHandle user = createUser(who, name);
5350         if (user == null) {
5351             return null;
5352         }
5353         long id = Binder.clearCallingIdentity();
5354         try {
5355             String profileOwnerPkg = profileOwnerComponent.getPackageName();
5356             final IPackageManager ipm = AppGlobals.getPackageManager();
5357             IActivityManager activityManager = ActivityManagerNative.getDefault();
5358
5359             final int userHandle = user.getIdentifier();
5360             try {
5361                 // Install the profile owner if not present.
5362                 if (!ipm.isPackageAvailable(profileOwnerPkg, userHandle)) {
5363                     ipm.installExistingPackageAsUser(profileOwnerPkg, userHandle);
5364                 }
5365
5366                 // Start user in background.
5367                 activityManager.startUserInBackground(userHandle);
5368             } catch (RemoteException e) {
5369                 Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e);
5370             }
5371
5372             setActiveAdmin(profileOwnerComponent, true, userHandle, adminExtras);
5373             setProfileOwner(profileOwnerComponent, ownerName, userHandle);
5374             return user;
5375         } finally {
5376             restoreCallingIdentity(id);
5377         }
5378     }
5379
5380     @Override
5381     public boolean removeUser(ComponentName who, UserHandle userHandle) {
5382         Preconditions.checkNotNull(who, "ComponentName is null");
5383         synchronized (this) {
5384             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5385
5386             long id = Binder.clearCallingIdentity();
5387             try {
5388                 return mUserManager.removeUser(userHandle.getIdentifier());
5389             } finally {
5390                 restoreCallingIdentity(id);
5391             }
5392         }
5393     }
5394
5395     @Override
5396     public boolean switchUser(ComponentName who, UserHandle userHandle) {
5397         Preconditions.checkNotNull(who, "ComponentName is null");
5398         synchronized (this) {
5399             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5400
5401             long id = Binder.clearCallingIdentity();
5402             try {
5403                 int userId = UserHandle.USER_OWNER;
5404                 if (userHandle != null) {
5405                     userId = userHandle.getIdentifier();
5406                 }
5407                 return ActivityManagerNative.getDefault().switchUser(userId);
5408             } catch (RemoteException e) {
5409                 Log.e(LOG_TAG, "Couldn't switch user", e);
5410                 return false;
5411             } finally {
5412                 restoreCallingIdentity(id);
5413             }
5414         }
5415     }
5416
5417     @Override
5418     public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
5419         Preconditions.checkNotNull(who, "ComponentName is null");
5420         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
5421
5422         synchronized (this) {
5423             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5424
5425             long id = Binder.clearCallingIdentity();
5426             try {
5427                 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
5428                 // if no restrictions were saved, mUserManager.getApplicationRestrictions
5429                 // returns null, but DPM method should return an empty Bundle as per JavaDoc
5430                 return bundle != null ? bundle : Bundle.EMPTY;
5431             } finally {
5432                 restoreCallingIdentity(id);
5433             }
5434         }
5435     }
5436
5437     @Override
5438     public void setUserRestriction(ComponentName who, String key, boolean enabled) {
5439         Preconditions.checkNotNull(who, "ComponentName is null");
5440         final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
5441         final int userHandle = user.getIdentifier();
5442         synchronized (this) {
5443             ActiveAdmin activeAdmin =
5444                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5445             boolean isDeviceOwner = isDeviceOwner(activeAdmin.info.getPackageName());
5446             if (!isDeviceOwner && userHandle != UserHandle.USER_OWNER
5447                     && DEVICE_OWNER_USER_RESTRICTIONS.contains(key)) {
5448                 throw new SecurityException("Profile owners cannot set user restriction " + key);
5449             }
5450             if (IMMUTABLE_USER_RESTRICTIONS.contains(key)) {
5451                 throw new SecurityException("User restriction " + key + " cannot be changed");
5452             }
5453             boolean alreadyRestricted = mUserManager.hasUserRestriction(key, user);
5454
5455             IAudioService iAudioService = null;
5456             if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)
5457                     || UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5458                 iAudioService = IAudioService.Stub.asInterface(
5459                         ServiceManager.getService(Context.AUDIO_SERVICE));
5460             }
5461
5462             long id = Binder.clearCallingIdentity();
5463             try {
5464                 if (enabled && !alreadyRestricted) {
5465                     if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
5466                         iAudioService.setMicrophoneMute(true, mContext.getPackageName(),
5467                                 userHandle);
5468                     } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5469                         iAudioService.setMasterMute(true, 0, mContext.getPackageName(),
5470                                 userHandle);
5471                     }
5472                     if (UserManager.DISALLOW_CONFIG_WIFI.equals(key)) {
5473                         Settings.Secure.putIntForUser(mContext.getContentResolver(),
5474                                 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0,
5475                                 userHandle);
5476                     } else if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
5477                         Settings.Secure.putIntForUser(mContext.getContentResolver(),
5478                                 Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF,
5479                                 userHandle);
5480                         Settings.Secure.putStringForUser(mContext.getContentResolver(),
5481                                 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, "",
5482                                 userHandle);
5483                     } else if (UserManager.DISALLOW_DEBUGGING_FEATURES.equals(key)) {
5484                         // Only disable adb if changing for primary user, since it is global
5485                         if (userHandle == UserHandle.USER_OWNER) {
5486                             Settings.Global.putStringForUser(mContext.getContentResolver(),
5487                                     Settings.Global.ADB_ENABLED, "0", userHandle);
5488                         }
5489                     } else if (UserManager.ENSURE_VERIFY_APPS.equals(key)) {
5490                         Settings.Global.putStringForUser(mContext.getContentResolver(),
5491                                 Settings.Global.PACKAGE_VERIFIER_ENABLE, "1",
5492                                 userHandle);
5493                         Settings.Global.putStringForUser(mContext.getContentResolver(),
5494                                 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1",
5495                                 userHandle);
5496                     } else if (UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES.equals(key)) {
5497                         Settings.Secure.putIntForUser(mContext.getContentResolver(),
5498                                 Settings.Secure.INSTALL_NON_MARKET_APPS, 0,
5499                                 userHandle);
5500                     }
5501                 }
5502                 mUserManager.setUserRestriction(key, enabled, user);
5503                 if (enabled != alreadyRestricted) {
5504                     if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
5505                         // Send out notifications however as some clients may want to reread the
5506                         // value which actually changed due to a restriction having been applied.
5507                         final String property = Settings.Secure.SYS_PROP_SETTING_VERSION;
5508                         long version = SystemProperties.getLong(property, 0) + 1;
5509                         SystemProperties.set(property, Long.toString(version));
5510
5511                         final String name = Settings.Secure.LOCATION_PROVIDERS_ALLOWED;
5512                         Uri url = Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
5513                         mContext.getContentResolver().notifyChange(url, null, true, userHandle);
5514                     }
5515                 }
5516                 if (!enabled && alreadyRestricted) {
5517                     if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
5518                         iAudioService.setMicrophoneMute(false, mContext.getPackageName(),
5519                                 userHandle);
5520                     } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5521                         iAudioService.setMasterMute(false, 0, mContext.getPackageName(),
5522                                 userHandle);
5523                     }
5524                 }
5525             } catch (RemoteException re) {
5526                 Slog.e(LOG_TAG, "Failed to talk to AudioService.", re);
5527             } finally {
5528                 restoreCallingIdentity(id);
5529             }
5530             sendChangedNotification(userHandle);
5531         }
5532     }
5533
5534     @Override
5535     public boolean setApplicationHidden(ComponentName who, String packageName,
5536             boolean hidden) {
5537         Preconditions.checkNotNull(who, "ComponentName is null");
5538         int callingUserId = UserHandle.getCallingUserId();
5539         synchronized (this) {
5540             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5541
5542             long id = Binder.clearCallingIdentity();
5543             try {
5544                 IPackageManager pm = AppGlobals.getPackageManager();
5545                 return pm.setApplicationHiddenSettingAsUser(packageName, hidden, callingUserId);
5546             } catch (RemoteException re) {
5547                 // shouldn't happen
5548                 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
5549             } finally {
5550                 restoreCallingIdentity(id);
5551             }
5552             return false;
5553         }
5554     }
5555
5556     @Override
5557     public boolean isApplicationHidden(ComponentName who, String packageName) {
5558         Preconditions.checkNotNull(who, "ComponentName is null");
5559         int callingUserId = UserHandle.getCallingUserId();
5560         synchronized (this) {
5561             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5562
5563             long id = Binder.clearCallingIdentity();
5564             try {
5565                 IPackageManager pm = AppGlobals.getPackageManager();
5566                 return pm.getApplicationHiddenSettingAsUser(packageName, callingUserId);
5567             } catch (RemoteException re) {
5568                 // shouldn't happen
5569                 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
5570             } finally {
5571                 restoreCallingIdentity(id);
5572             }
5573             return false;
5574         }
5575     }
5576
5577     @Override
5578     public void enableSystemApp(ComponentName who, String packageName) {
5579         Preconditions.checkNotNull(who, "ComponentName is null");
5580         synchronized (this) {
5581             // This API can only be called by an active device admin,
5582             // so try to retrieve it to check that the caller is one.
5583             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5584
5585             int userId = UserHandle.getCallingUserId();
5586             long id = Binder.clearCallingIdentity();
5587
5588             try {
5589                 if (DBG) {
5590                     Slog.v(LOG_TAG, "installing " + packageName + " for "
5591                             + userId);
5592                 }
5593
5594                 UserManager um = UserManager.get(mContext);
5595                 UserInfo primaryUser = um.getProfileParent(userId);
5596
5597                 // Call did not come from a managed profile
5598                 if (primaryUser == null) {
5599                     primaryUser = um.getUserInfo(userId);
5600                 }
5601
5602                 IPackageManager pm = AppGlobals.getPackageManager();
5603                 if (!isSystemApp(pm, packageName, primaryUser.id)) {
5604                     throw new IllegalArgumentException("Only system apps can be enabled this way.");
5605                 }
5606
5607                 // Install the app.
5608                 pm.installExistingPackageAsUser(packageName, userId);
5609
5610             } catch (RemoteException re) {
5611                 // shouldn't happen
5612                 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
5613             } finally {
5614                 restoreCallingIdentity(id);
5615             }
5616         }
5617     }
5618
5619     @Override
5620     public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
5621         Preconditions.checkNotNull(who, "ComponentName is null");
5622         synchronized (this) {
5623             // This API can only be called by an active device admin,
5624             // so try to retrieve it to check that the caller is one.
5625             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5626
5627             int userId = UserHandle.getCallingUserId();
5628             long id = Binder.clearCallingIdentity();
5629
5630             try {
5631                 UserManager um = UserManager.get(mContext);
5632                 UserInfo primaryUser = um.getProfileParent(userId);
5633
5634                 // Call did not come from a managed profile.
5635                 if (primaryUser == null) {
5636                     primaryUser = um.getUserInfo(userId);
5637                 }
5638
5639                 IPackageManager pm = AppGlobals.getPackageManager();
5640                 List<ResolveInfo> activitiesToEnable = pm.queryIntentActivities(intent,
5641                         intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5642                         0, // no flags
5643                         primaryUser.id);
5644
5645                 if (DBG) Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
5646                 int numberOfAppsInstalled = 0;
5647                 if (activitiesToEnable != null) {
5648                     for (ResolveInfo info : activitiesToEnable) {
5649                         if (info.activityInfo != null) {
5650                             String packageName = info.activityInfo.packageName;
5651                             if (isSystemApp(pm, packageName, primaryUser.id)) {
5652                                 numberOfAppsInstalled++;
5653                                 pm.installExistingPackageAsUser(packageName, userId);
5654                             } else {
5655                                 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
5656                                         + " system app");
5657                             }
5658                         }
5659                     }
5660                 }
5661                 return numberOfAppsInstalled;
5662             } catch (RemoteException e) {
5663                 // shouldn't happen
5664                 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
5665                 return 0;
5666             } finally {
5667                 restoreCallingIdentity(id);
5668             }
5669         }
5670     }
5671
5672     private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
5673             throws RemoteException {
5674         ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
5675                 userId);
5676         if (appInfo == null) {
5677             throw new IllegalArgumentException("The application " + packageName +
5678                     " is not present on this device");
5679         }
5680         return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5681     }
5682
5683     @Override
5684     public void setAccountManagementDisabled(ComponentName who, String accountType,
5685             boolean disabled) {
5686         if (!mHasFeature) {
5687             return;
5688         }
5689         Preconditions.checkNotNull(who, "ComponentName is null");
5690         synchronized (this) {
5691             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5692                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5693             if (disabled) {
5694                 ap.accountTypesWithManagementDisabled.add(accountType);
5695             } else {
5696                 ap.accountTypesWithManagementDisabled.remove(accountType);
5697             }
5698             saveSettingsLocked(UserHandle.getCallingUserId());
5699         }
5700     }
5701
5702     @Override
5703     public String[] getAccountTypesWithManagementDisabled() {
5704         return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
5705     }
5706
5707     @Override
5708     public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
5709         enforceCrossUserPermission(userId);
5710         if (!mHasFeature) {
5711             return null;
5712         }
5713         synchronized (this) {
5714             DevicePolicyData policy = getUserData(userId);
5715             final int N = policy.mAdminList.size();
5716             HashSet<String> resultSet = new HashSet<String>();
5717             for (int i = 0; i < N; i++) {
5718                 ActiveAdmin admin = policy.mAdminList.get(i);
5719                 resultSet.addAll(admin.accountTypesWithManagementDisabled);
5720             }
5721             return resultSet.toArray(new String[resultSet.size()]);
5722         }
5723     }
5724
5725     @Override
5726     public void setUninstallBlocked(ComponentName who, String packageName,
5727             boolean uninstallBlocked) {
5728         Preconditions.checkNotNull(who, "ComponentName is null");
5729         final int userId = UserHandle.getCallingUserId();
5730         synchronized (this) {
5731             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5732
5733             long id = Binder.clearCallingIdentity();
5734             try {
5735                 IPackageManager pm = AppGlobals.getPackageManager();
5736                 pm.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
5737             } catch (RemoteException re) {
5738                 // Shouldn't happen.
5739                 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
5740             } finally {
5741                 restoreCallingIdentity(id);
5742             }
5743         }
5744     }
5745
5746     @Override
5747     public boolean isUninstallBlocked(ComponentName who, String packageName) {
5748         // This function should return true if and only if the package is blocked by
5749         // setUninstallBlocked(). It should still return false for other cases of blocks, such as
5750         // when the package is a system app, or when it is an active device admin.
5751         final int userId = UserHandle.getCallingUserId();
5752
5753         synchronized (this) {
5754             if (who != null) {
5755                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5756             }
5757
5758             long id = Binder.clearCallingIdentity();
5759             try {
5760                 IPackageManager pm = AppGlobals.getPackageManager();
5761                 return pm.getBlockUninstallForUser(packageName, userId);
5762             } catch (RemoteException re) {
5763                 // Shouldn't happen.
5764                 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
5765             } finally {
5766                 restoreCallingIdentity(id);
5767             }
5768         }
5769         return false;
5770     }
5771
5772     @Override
5773     public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
5774         if (!mHasFeature) {
5775             return;
5776         }
5777         Preconditions.checkNotNull(who, "ComponentName is null");
5778         synchronized (this) {
5779             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5780                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5781             if (admin.disableCallerId != disabled) {
5782                 admin.disableCallerId = disabled;
5783                 saveSettingsLocked(UserHandle.getCallingUserId());
5784             }
5785         }
5786     }
5787
5788     @Override
5789     public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
5790         if (!mHasFeature) {
5791             return false;
5792         }
5793         Preconditions.checkNotNull(who, "ComponentName is null");
5794         synchronized (this) {
5795             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5796                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5797             return admin.disableCallerId;
5798         }
5799     }
5800
5801     @Override
5802     public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
5803         // TODO: Should there be a check to make sure this relationship is within a profile group?
5804         //enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5805         synchronized (this) {
5806             ActiveAdmin admin = getProfileOwnerAdmin(userId);
5807             return (admin != null) ? admin.disableCallerId : false;
5808         }
5809     }
5810
5811     @Override
5812     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5813             Intent originalIntent) {
5814         final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(
5815                 actualLookupKey, actualContactId, originalIntent);
5816         final int callingUserId = UserHandle.getCallingUserId();
5817
5818         final long ident = Binder.clearCallingIdentity();
5819         try {
5820             synchronized (this) {
5821                 final int managedUserId = getManagedUserId(callingUserId);
5822                 if (managedUserId < 0) {
5823                     return;
5824                 }
5825                 if (getCrossProfileCallerIdDisabledForUser(managedUserId)) {
5826                     if (VERBOSE_LOG) {
5827                         Log.v(LOG_TAG,
5828                                 "Cross-profile contacts access disabled for user " + managedUserId);
5829                     }
5830                     return;
5831                 }
5832                 ContactsInternal.startQuickContactWithErrorToastForUser(
5833                         mContext, intent, new UserHandle(managedUserId));
5834             }
5835         } finally {
5836             Binder.restoreCallingIdentity(ident);
5837         }
5838     }
5839
5840     /**
5841      * @return the user ID of the managed user that is linked to the current user, if any.
5842      * Otherwise -1.
5843      */
5844     public int getManagedUserId(int callingUserId) {
5845         if (VERBOSE_LOG) {
5846             Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
5847         }
5848
5849         for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
5850             if (ui.id == callingUserId || !ui.isManagedProfile()) {
5851                 continue; // Caller user self, or not a managed profile.  Skip.
5852             }
5853             if (VERBOSE_LOG) {
5854                 Log.v(LOG_TAG, "Managed user=" + ui.id);
5855             }
5856             return ui.id;
5857         }
5858         if (VERBOSE_LOG) {
5859             Log.v(LOG_TAG, "Managed user not found.");
5860         }
5861         return -1;
5862     }
5863
5864     @Override
5865     public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
5866         if (!mHasFeature) {
5867             return;
5868         }
5869         Preconditions.checkNotNull(who, "ComponentName is null");
5870         synchronized (this) {
5871             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5872                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5873             if (admin.disableBluetoothContactSharing != disabled) {
5874                 admin.disableBluetoothContactSharing = disabled;
5875                 saveSettingsLocked(UserHandle.getCallingUserId());
5876             }
5877         }
5878     }
5879
5880     @Override
5881     public boolean getBluetoothContactSharingDisabled(ComponentName who) {
5882         if (!mHasFeature) {
5883             return false;
5884         }
5885         Preconditions.checkNotNull(who, "ComponentName is null");
5886         synchronized (this) {
5887             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5888                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5889             return admin.disableBluetoothContactSharing;
5890         }
5891     }
5892
5893     @Override
5894     public boolean getBluetoothContactSharingDisabledForUser(int userId) {
5895         // TODO: Should there be a check to make sure this relationship is
5896         // within a profile group?
5897         // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5898         synchronized (this) {
5899             ActiveAdmin admin = getProfileOwnerAdmin(userId);
5900             return (admin != null) ? admin.disableBluetoothContactSharing : false;
5901         }
5902     }
5903
5904     /**
5905      * Sets which packages may enter lock task mode.
5906      *
5907      * This function can only be called by the device owner.
5908      * @param packages The list of packages allowed to enter lock task mode.
5909      */
5910     @Override
5911     public void setLockTaskPackages(ComponentName who, String[] packages)
5912             throws SecurityException {
5913         Preconditions.checkNotNull(who, "ComponentName is null");
5914         synchronized (this) {
5915             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5916
5917             int userHandle = Binder.getCallingUserHandle().getIdentifier();
5918             setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
5919         }
5920     }
5921
5922     private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
5923         DevicePolicyData policy = getUserData(userHandle);
5924         policy.mLockTaskPackages = packages;
5925
5926         // Store the settings persistently.
5927         saveSettingsLocked(userHandle);
5928         updateLockTaskPackagesLocked(packages, userHandle);
5929     }
5930
5931     /**
5932      * This function returns the list of components allowed to start the task lock mode.
5933      */
5934     @Override
5935     public String[] getLockTaskPackages(ComponentName who) {
5936         Preconditions.checkNotNull(who, "ComponentName is null");
5937         synchronized (this) {
5938             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5939             int userHandle = Binder.getCallingUserHandle().getIdentifier();
5940             final List<String> packages = getLockTaskPackagesLocked(userHandle);
5941             return packages.toArray(new String[packages.size()]);
5942         }
5943     }
5944
5945     private List<String> getLockTaskPackagesLocked(int userHandle) {
5946         final DevicePolicyData policy = getUserData(userHandle);
5947         return policy.mLockTaskPackages;
5948     }
5949
5950     /**
5951      * This function lets the caller know whether the given package is allowed to start the
5952      * lock task mode.
5953      * @param pkg The package to check
5954      */
5955     @Override
5956     public boolean isLockTaskPermitted(String pkg) {
5957         // Get current user's devicepolicy
5958         int uid = Binder.getCallingUid();
5959         int userHandle = UserHandle.getUserId(uid);
5960         DevicePolicyData policy = getUserData(userHandle);
5961         synchronized (this) {
5962             for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
5963                 String lockTaskPackage = policy.mLockTaskPackages.get(i);
5964
5965                 // If the given package equals one of the packages stored our list,
5966                 // we allow this package to start lock task mode.
5967                 if (lockTaskPackage.equals(pkg)) {
5968                     return true;
5969                 }
5970             }
5971         }
5972         return false;
5973     }
5974
5975     @Override
5976     public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
5977         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
5978             throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
5979         }
5980         synchronized (this) {
5981             final DevicePolicyData policy = getUserData(userHandle);
5982             Bundle adminExtras = new Bundle();
5983             adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
5984             for (ActiveAdmin admin : policy.mAdminList) {
5985                 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
5986                 boolean ownsProfile = (getProfileOwner(userHandle) != null
5987                         && getProfileOwner(userHandle).equals(admin.info.getPackageName()));
5988                 if (ownsDevice || ownsProfile) {
5989                     if (isEnabled) {
5990                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
5991                                 adminExtras, null);
5992                     } else {
5993                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
5994                     }
5995                 }
5996             }
5997         }
5998     }
5999
6000     @Override
6001     public void setGlobalSetting(ComponentName who, String setting, String value) {
6002         final ContentResolver contentResolver = mContext.getContentResolver();
6003         Preconditions.checkNotNull(who, "ComponentName is null");
6004
6005         synchronized (this) {
6006             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6007
6008             // Some settings are no supported any more. However we do not want to throw a
6009             // SecurityException to avoid breaking apps.
6010             if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
6011                 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
6012                 return;
6013             }
6014
6015             if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
6016                 throw new SecurityException(String.format(
6017                         "Permission denial: device owners cannot update %1$s", setting));
6018             }
6019
6020             if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
6021                 // ignore if it contradicts an existing policy
6022                 long timeMs = getMaximumTimeToLock(who, UserHandle.getCallingUserId());
6023                 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
6024                     return;
6025                 }
6026             }
6027
6028             long id = Binder.clearCallingIdentity();
6029             try {
6030                 Settings.Global.putString(contentResolver, setting, value);
6031             } finally {
6032                 restoreCallingIdentity(id);
6033             }
6034         }
6035     }
6036
6037     @Override
6038     public void setSecureSetting(ComponentName who, String setting, String value) {
6039         Preconditions.checkNotNull(who, "ComponentName is null");
6040         int callingUserId = UserHandle.getCallingUserId();
6041         final ContentResolver contentResolver = mContext.getContentResolver();
6042
6043         synchronized (this) {
6044             ActiveAdmin activeAdmin =
6045                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6046
6047             if (isDeviceOwner(activeAdmin.info.getPackageName())) {
6048                 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
6049                     throw new SecurityException(String.format(
6050                             "Permission denial: Device owners cannot update %1$s", setting));
6051                 }
6052             } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
6053                 throw new SecurityException(String.format(
6054                         "Permission denial: Profile owners cannot update %1$s", setting));
6055             }
6056
6057             long id = Binder.clearCallingIdentity();
6058             try {
6059                 Settings.Secure.putStringForUser(contentResolver, setting, value, callingUserId);
6060             } finally {
6061                 restoreCallingIdentity(id);
6062             }
6063         }
6064     }
6065
6066     @Override
6067     public void setMasterVolumeMuted(ComponentName who, boolean on) {
6068         Preconditions.checkNotNull(who, "ComponentName is null");
6069         synchronized (this) {
6070             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6071             int userId = UserHandle.getCallingUserId();
6072             long identity = Binder.clearCallingIdentity();
6073             try {
6074                 IAudioService iAudioService = IAudioService.Stub.asInterface(
6075                         ServiceManager.getService(Context.AUDIO_SERVICE));
6076                 iAudioService.setMasterMute(on, 0, mContext.getPackageName(), userId);
6077             } catch (RemoteException re) {
6078                 Slog.e(LOG_TAG, "Failed to setMasterMute", re);
6079             } finally {
6080                 Binder.restoreCallingIdentity(identity);
6081             }
6082         }
6083     }
6084
6085     @Override
6086     public boolean isMasterVolumeMuted(ComponentName who) {
6087         Preconditions.checkNotNull(who, "ComponentName is null");
6088         synchronized (this) {
6089             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6090
6091             AudioManager audioManager =
6092                     (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
6093             return audioManager.isMasterMute();
6094         }
6095     }
6096
6097     @Override
6098     public void setUserIcon(ComponentName who, Bitmap icon) {
6099         synchronized (this) {
6100             Preconditions.checkNotNull(who, "ComponentName is null");
6101             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6102
6103             int userId = UserHandle.getCallingUserId();
6104             long id = Binder.clearCallingIdentity();
6105             try {
6106                 mUserManager.setUserIcon(userId, icon);
6107             } finally {
6108                 restoreCallingIdentity(id);
6109             }
6110         }
6111     }
6112
6113     @Override
6114     public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
6115         Preconditions.checkNotNull(who, "ComponentName is null");
6116         synchronized (this) {
6117             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6118         }
6119         final int userId = UserHandle.getCallingUserId();
6120         LockPatternUtils utils = new LockPatternUtils(mContext);
6121
6122         long ident = Binder.clearCallingIdentity();
6123         try {
6124             // disallow disabling the keyguard if a password is currently set
6125             if (disabled && utils.isSecure(userId)) {
6126                 return false;
6127             }
6128             utils.setLockScreenDisabled(disabled, userId);
6129         } finally {
6130             Binder.restoreCallingIdentity(ident);
6131         }
6132         return true;
6133     }
6134
6135     @Override
6136     public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
6137         int userId = UserHandle.getCallingUserId();
6138         synchronized (this) {
6139             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6140             DevicePolicyData policy = getUserData(userId);
6141             if (policy.mStatusBarDisabled != disabled) {
6142                 if (!setStatusBarDisabledInternal(disabled, userId)) {
6143                     return false;
6144                 }
6145                 policy.mStatusBarDisabled = disabled;
6146                 saveSettingsLocked(userId);
6147             }
6148         }
6149         return true;
6150     }
6151
6152     private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
6153         long ident = Binder.clearCallingIdentity();
6154         try {
6155             IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
6156                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
6157             if (statusBarService != null) {
6158                 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
6159                 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
6160                 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
6161                 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
6162                 return true;
6163             }
6164         } catch (RemoteException e) {
6165             Slog.e(LOG_TAG, "Failed to disable the status bar", e);
6166         } finally {
6167             Binder.restoreCallingIdentity(ident);
6168         }
6169         return false;
6170     }
6171
6172     /**
6173      * We need to update the internal state of whether a user has completed setup once. After
6174      * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
6175      * as we don't trust any apps that might try to reset it.
6176      * <p>
6177      * Unfortunately, we don't know which user's setup state was changed, so we write all of
6178      * them.
6179      */
6180     void updateUserSetupComplete() {
6181         List<UserInfo> users = mUserManager.getUsers(true);
6182         ContentResolver resolver = mContext.getContentResolver();
6183         final int N = users.size();
6184         for (int i = 0; i < N; i++) {
6185             int userHandle = users.get(i).id;
6186             if (Settings.Secure.getIntForUser(resolver, Settings.Secure.USER_SETUP_COMPLETE, 0,
6187                     userHandle) != 0) {
6188                 DevicePolicyData policy = getUserData(userHandle);
6189                 if (!policy.mUserSetupComplete) {
6190                     policy.mUserSetupComplete = true;
6191                     synchronized (this) {
6192                         // The DeviceInitializer was whitelisted but now should be removed.
6193                         removeDeviceInitializerFromLockTaskPackages(userHandle);
6194                         saveSettingsLocked(userHandle);
6195                     }
6196                 }
6197             }
6198         }
6199     }
6200
6201     private void addDeviceInitializerToLockTaskPackagesLocked(int userHandle) {
6202         if (hasUserSetupCompleted(userHandle)) {
6203             return;
6204         }
6205
6206         final String deviceInitializerPackage = getDeviceInitializer();
6207         if (deviceInitializerPackage == null) {
6208             return;
6209         }
6210
6211         final List<String> packages = getLockTaskPackagesLocked(userHandle);
6212         if (!packages.contains(deviceInitializerPackage)) {
6213             packages.add(deviceInitializerPackage);
6214             setLockTaskPackagesLocked(userHandle, packages);
6215         }
6216     }
6217
6218     private void removeDeviceInitializerFromLockTaskPackages(int userHandle) {
6219         final String deviceInitializerPackage = getDeviceInitializer();
6220         if (deviceInitializerPackage == null) {
6221             return;
6222         }
6223
6224         List<String> packages = getLockTaskPackagesLocked(userHandle);
6225         if (packages.remove(deviceInitializerPackage)) {
6226             setLockTaskPackagesLocked(userHandle, packages);
6227         }
6228     }
6229
6230     private class SetupContentObserver extends ContentObserver {
6231
6232         private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
6233                 Settings.Secure.USER_SETUP_COMPLETE);
6234
6235         public SetupContentObserver(Handler handler) {
6236             super(handler);
6237         }
6238
6239         void register(ContentResolver resolver) {
6240             resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
6241         }
6242
6243         @Override
6244         public void onChange(boolean selfChange, Uri uri) {
6245             if (mUserSetupComplete.equals(uri)) {
6246                 updateUserSetupComplete();
6247             }
6248         }
6249     }
6250
6251     private final class LocalService extends DevicePolicyManagerInternal {
6252         private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
6253
6254         @Override
6255         public List<String> getCrossProfileWidgetProviders(int profileId) {
6256             synchronized (DevicePolicyManagerService.this) {
6257                 if (mDeviceOwner == null) {
6258                     return Collections.emptyList();
6259                 }
6260                 ComponentName ownerComponent = mDeviceOwner.getProfileOwnerComponent(profileId);
6261                 if (ownerComponent == null) {
6262                     return Collections.emptyList();
6263                 }
6264
6265                 DevicePolicyData policy = getUserDataUnchecked(profileId);
6266                 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
6267
6268                 if (admin == null || admin.crossProfileWidgetProviders == null
6269                         || admin.crossProfileWidgetProviders.isEmpty()) {
6270                     return Collections.emptyList();
6271                 }
6272
6273                 return admin.crossProfileWidgetProviders;
6274             }
6275         }
6276
6277         @Override
6278         public void addOnCrossProfileWidgetProvidersChangeListener(
6279                 OnCrossProfileWidgetProvidersChangeListener listener) {
6280             synchronized (DevicePolicyManagerService.this) {
6281                 if (mWidgetProviderListeners == null) {
6282                     mWidgetProviderListeners = new ArrayList<>();
6283                 }
6284                 if (!mWidgetProviderListeners.contains(listener)) {
6285                     mWidgetProviderListeners.add(listener);
6286                 }
6287             }
6288         }
6289
6290         @Override
6291         public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
6292             final int userId = UserHandle.getUserId(uid);
6293             synchronized(DevicePolicyManagerService.this) {
6294                 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
6295             }
6296         }
6297
6298         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
6299             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
6300             synchronized (DevicePolicyManagerService.this) {
6301                 listeners = new ArrayList<>(mWidgetProviderListeners);
6302             }
6303             final int listenerCount = listeners.size();
6304             for (int i = 0; i < listenerCount; i++) {
6305                 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
6306                 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
6307             }
6308         }
6309     }
6310
6311     /**
6312      * Returns true if specified admin is allowed to limit passwords and has a
6313      * {@code passwordQuality} of at least {@code minPasswordQuality}
6314      */
6315     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
6316         if (admin.passwordQuality < minPasswordQuality) {
6317             return false;
6318         }
6319         return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
6320     }
6321
6322     @Override
6323     public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
6324         if (policy != null && !policy.isValid()) {
6325             throw new IllegalArgumentException("Invalid system update policy.");
6326         }
6327         synchronized (this) {
6328             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6329             if (policy == null) {
6330                 mDeviceOwner.clearSystemUpdatePolicy();
6331             } else {
6332                 mDeviceOwner.setSystemUpdatePolicy(policy);
6333             }
6334             mDeviceOwner.writeOwnerFile();
6335         }
6336         mContext.sendBroadcastAsUser(
6337                 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
6338                 UserHandle.OWNER);
6339     }
6340
6341     @Override
6342     public SystemUpdatePolicy getSystemUpdatePolicy() {
6343         synchronized (this) {
6344             SystemUpdatePolicy policy =  mDeviceOwner.getSystemUpdatePolicy();
6345             if (policy != null && !policy.isValid()) {
6346                 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
6347                 return null;
6348             }
6349             return policy;
6350         }
6351     }
6352
6353     /**
6354      * Checks if the caller of the method is the device owner app or device initialization app.
6355      *
6356      * @param callerUid UID of the caller.
6357      * @return true if the caller is the device owner app or device initializer.
6358      */
6359     private boolean isCallerDeviceOwnerOrInitializer(int callerUid) {
6360         String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
6361         for (String pkg : pkgs) {
6362             if (isDeviceOwner(pkg) || isDeviceInitializer(pkg)) {
6363                 return true;
6364             }
6365         }
6366         return false;
6367     }
6368
6369     @Override
6370     public void notifyPendingSystemUpdate(long updateReceivedTime) {
6371         mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
6372                 "Only the system update service can broadcast update information");
6373
6374         if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
6375             Slog.w(LOG_TAG, "Only the system update service in the primary user" +
6376                     "can broadcast update information.");
6377             return;
6378         }
6379         Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
6380         intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
6381                 updateReceivedTime);
6382
6383         synchronized (this) {
6384             String deviceOwnerPackage = getDeviceOwner();
6385             if (deviceOwnerPackage == null) {
6386                 return;
6387             }
6388
6389             ActivityInfo[] receivers = null;
6390             try {
6391                 receivers  = mContext.getPackageManager().getPackageInfo(
6392                         deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
6393             } catch (NameNotFoundException e) {
6394                 Log.e(LOG_TAG, "Cannot find device owner package", e);
6395             }
6396             if (receivers != null) {
6397                 long ident = Binder.clearCallingIdentity();
6398                 try {
6399                     for (int i = 0; i < receivers.length; i++) {
6400                         if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
6401                             intent.setComponent(new ComponentName(deviceOwnerPackage,
6402                                     receivers[i].name));
6403                             mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
6404                         }
6405                     }
6406                 } finally {
6407                     Binder.restoreCallingIdentity(ident);
6408                 }
6409             }
6410         }
6411     }
6412
6413     @Override
6414     public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
6415         int userId = UserHandle.getCallingUserId();
6416         synchronized (this) {
6417             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6418             DevicePolicyData userPolicy = getUserData(userId);
6419             if (userPolicy.mPermissionPolicy != policy) {
6420                 userPolicy.mPermissionPolicy = policy;
6421                 saveSettingsLocked(userId);
6422             }
6423         }
6424     }
6425
6426     @Override
6427     public int getPermissionPolicy(ComponentName admin) throws RemoteException {
6428         int userId = UserHandle.getCallingUserId();
6429         synchronized (this) {
6430             DevicePolicyData userPolicy = getUserData(userId);
6431             return userPolicy.mPermissionPolicy;
6432         }
6433     }
6434
6435     @Override
6436     public boolean setPermissionGrantState(ComponentName admin, String packageName,
6437             String permission, int grantState) throws RemoteException {
6438         UserHandle user = Binder.getCallingUserHandle();
6439         synchronized (this) {
6440             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6441             long ident = Binder.clearCallingIdentity();
6442             try {
6443                 final ApplicationInfo ai = AppGlobals.getPackageManager()
6444                         .getApplicationInfo(packageName, 0, user.getIdentifier());
6445                 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
6446                 if (targetSdkVersion < android.os.Build.VERSION_CODES.M) {
6447                     return false;
6448                 }
6449                 if (!isRuntimePermission(permission)) {
6450                     EventLog.writeEvent(0x534e4554, "62623498", user.getIdentifier(), "");
6451                     return false;
6452                 }
6453                 final PackageManager packageManager = mContext.getPackageManager();
6454                 switch (grantState) {
6455                     case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
6456                         packageManager.grantRuntimePermission(packageName, permission, user);
6457                         packageManager.updatePermissionFlags(permission, packageName,
6458                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6459                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
6460                     } break;
6461
6462                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
6463                         packageManager.revokeRuntimePermission(packageName,
6464                                 permission, user);
6465                         packageManager.updatePermissionFlags(permission, packageName,
6466                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6467                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
6468                     } break;
6469
6470                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
6471                         packageManager.updatePermissionFlags(permission, packageName,
6472                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
6473                     } break;
6474                 }
6475                 return true;
6476             } catch (SecurityException se) {
6477                 return false;
6478             } catch (NameNotFoundException e) {
6479                 return false;
6480             } finally {
6481                 Binder.restoreCallingIdentity(ident);
6482             }
6483         }
6484     }
6485
6486     public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
6487         final PackageManager packageManager = mContext.getPackageManager();
6488         PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
6489         return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
6490                 == PermissionInfo.PROTECTION_DANGEROUS;
6491     }
6492
6493     @Override
6494     public int getPermissionGrantState(ComponentName admin, String packageName,
6495             String permission) throws RemoteException {
6496         PackageManager packageManager = mContext.getPackageManager();
6497
6498         UserHandle user = Binder.getCallingUserHandle();
6499         synchronized (this) {
6500             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6501             long ident = Binder.clearCallingIdentity();
6502             try {
6503                 int granted = AppGlobals.getPackageManager().checkPermission(permission,
6504                         packageName, user.getIdentifier());
6505                 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
6506                 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
6507                         != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
6508                     // Not controlled by policy
6509                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
6510                 } else {
6511                     // Policy controlled so return result based on permission grant state
6512                     return granted == PackageManager.PERMISSION_GRANTED
6513                             ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
6514                             : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
6515                 }
6516             } finally {
6517                 Binder.restoreCallingIdentity(ident);
6518             }
6519         }
6520     }
6521 }