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