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