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