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