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