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