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