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