OSDN Git Service

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