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