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